pandas 在DataFrame中获取给定索引的位置 [英] pandas get position of a given index in DataFrame

查看:125
本文介绍了 pandas 在DataFrame中获取给定索引的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的DataFrame:

Let's say I have a DataFrame like this:

df
     A  B
5    0  1
18   2  3
125  4  5

其中5, 18, 125是索引

我想在某个索引之前(或之后)得到该行.例如,我有索引18(例如,通过执行df[df.A==2].index),并且我想先获得该行,并且我不知道该行具有5作为索引.

I'd like to get the line before (or after) a certain index. For instance, I have index 18 (eg. by doing df[df.A==2].index), and I want to get the line before, and I don't know that this line has 5 as an index.

2个子问题:

  • 如何获取索引18的位置?像df.loc[18].get_position()这样会返回1的东西,所以我可以在df.iloc[df.loc[18].get_position()-1]
  • 之前到达该行
  • 还有其他解决方案吗,有点像带有grep的选项-C-A-B?
  • How can I get the position of index 18? Something like df.loc[18].get_position() which would return 1 so I could reach the line before with df.iloc[df.loc[18].get_position()-1]
  • Is there another solution, a bit like options -C, -A or -B with grep ?

推荐答案

第一个问题:

base = df.index.get_indexer_for((df[df.A == 2].index))

或者

base = df.index.get_loc(18)

要获取周围的东西:

mask = pd.Index(base).union(pd.Index(base - 1)).union(pd.Index(base + 1))

我使用索引和联合来删除重复项.您可能需要保留它们,在这种情况下,可以使用np.concatenate

I used Indexes and unions to remove duplicates. You may want to keep them, in which case you can use np.concatenate

请注意第一行或最后一行的匹配:)

Be careful with matches on the very first or last rows :)

这篇关于 pandas 在DataFrame中获取给定索引的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆