【问题标题】:pandas get position of a given index in DataFramepandas 获取 DataFrame 中给定索引的位置
【发布时间】:2022-11-29 17:52:15
【问题描述】:

假设我有一个这样的 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

    小心第一行或最后一行的匹配:)

    【讨论】:

      【解决方案2】:

      如果需要转换 1 个以上的索引,可以使用np.where

      例子:

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

      import pandas as pd
      import numpy as np
      
      df = pd.DataFrame({"A": [0,2,4], "B": [1,3,5]}, index=[5,18,125])
      np.where(df.index.isin([18,125]))
      

      输出:

      (array([1, 2]),)
      

      【讨论】:

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