【问题标题】:pandas get position of a given index in DataFramepandas 在 DataFrame 中获取给定索引的位置
【发布时间】:2016-07-29 20:23:05
【问题描述】:

假设我有一个这样的 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() 这样的东西会返回1,所以我可以在之前使用df.iloc[df.loc[18].get_position()-1] 到达线路
  • 还有其他解决方案吗,有点像选项-C-A-B with grep?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    第一个问题:

    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

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

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 2013-02-15
      • 2019-05-01
      • 2017-07-12
      • 2023-03-03
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      相关资源
      最近更新 更多