pandas 获取给定索引在 DataFrame 中的位置
pandas get position of a given index in DataFrame
假设我有一个这样的 DataFrame:
df
A B
5 0 1
18 2 3
125 4 5
其中 5, 18, 125
是索引
我想获取某个索引之前(或之后)的行。例如,我有索引18
(例如通过df[df.A==2].index
),我想得到之前的行,但我不知道这一行有5
作为索引.
2个子问题:
- 如何获取索引
18
的位置?像 df.loc[18].get_position()
这样的东西会 return 1
所以我可以用 df.iloc[df.loc[18].get_position()-1]
到达之前的那条线
- 有没有其他解决方案,有点像 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
注意第一行或最后一行的匹配:)
假设我有一个这样的 DataFrame:
df
A B
5 0 1
18 2 3
125 4 5
其中 5, 18, 125
是索引
我想获取某个索引之前(或之后)的行。例如,我有索引18
(例如通过df[df.A==2].index
),我想得到之前的行,但我不知道这一行有5
作为索引.
2个子问题:
- 如何获取索引
18
的位置?像df.loc[18].get_position()
这样的东西会 return1
所以我可以用df.iloc[df.loc[18].get_position()-1]
到达之前的那条线
- 有没有其他解决方案,有点像 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
注意第一行或最后一行的匹配:)