pandas 在 DataFrame 中获取给定索引的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28837633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas get position of a given index in DataFrame
提问by jrjc
Let's say I have a DataFrame like this:
假设我有一个这样的 DataFrame:
df
A B
5 0 1
18 2 3
125 4 5
where 5, 18, 125are the index
5, 18, 125索引在哪里
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 5as an index.
我想在某个索引之前(或之后)获取该行。例如,我有索引18(例如,通过执行df[df.A==2].index),并且我想之前获得该行,但我不知道该行5作为索引。
2 sub-questions:
2个子问题:
- How can I get the position of index
18? Something likedf.loc[18].get_position()which would return1so I could reach the line before withdf.iloc[df.loc[18].get_position()-1] - Is there another solution, a bit like options
-C,-Aor-Bwith grep ?
- 如何获得 index 的位置
18?类似的东西df.loc[18].get_position()会回来,1所以我可以在之前到达线路df.iloc[df.loc[18].get_position()-1] - 有另一种解决办法,有点像选择
-C,-A或者-B使用grep?
回答by TomAugspurger
For your first question:
对于你的第一个问题:
base = df.index.get_indexer_for((df[df.A == 2].index))
or alternatively
或者
base = df.index.get_loc(18)
To get the surrounding ones:
要获取周围的:
mask = pd.Index(base).union(pd.Index(base - 1)).union(pd.Index(base + 1))
I used Indexes and unions to remove duplicates. You may want to keep them, in which case you can use np.concatenate
我使用索引和联合来删除重复项。您可能希望保留它们,在这种情况下您可以使用np.concatenate
Be careful with matches on the very first or last rows :)
小心第一行或最后一行的匹配:)

