【问题标题】:Getting the integer index of a Pandas DataFrame row fulfilling a condition?获取满足条件的 Pandas DataFrame 行的整数索引?
【发布时间】:2013-08-14 11:46:17
【问题描述】:

我有以下数据框:

   a  b  c
b
2  1  2  3
5  4  5  6

如您所见,b 列用作索引。我想获得满足('b' == 5) 的行的序号,在本例中为1

被测试的列可以是索引列(在这种情况下与 b 一样)或常规列,例如我可能想找到满足('c' == 6) 的行的索引。

【问题讨论】:

    标签: python numpy pandas


    【解决方案1】:

    Index.get_loc 和一般情况:

    >>> import pandas as pd
    >>> import numpy as np
    
    
    >>> df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                      columns = list('abc'),
                      index=pd.Series([2,5], name='b'))
    >>> df
       a  b  c
    b
    2  1  2  3
    5  4  5  6
    >>> df.index.get_loc(df.index[df['b'] == 5][0])
    1
    

    【讨论】:

      【解决方案2】:

      请改用Index.get_loc

      重用@unutbu 的设置代码,您将获得相同的结果。

      >>> import pandas as pd
      >>> import numpy as np
      
      
      >>> df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                        columns = list('abc'),
                        index=pd.Series([2,5], name='b'))
      >>> df
         a  b  c
      b
      2  1  2  3
      5  4  5  6
      >>> df.index.get_loc(5)
      1
      

      【讨论】:

      • 这不是 OP 想要的。您正在回答这个问题,“给定索引的序数位置是什么?”。 OP 想知道,“满足给定条件的行的序数位置是什么?”。也就是说,输入是特定条件,例如(df.b == 5) 或 (df.c == 6)。
      • OP 说“被测试的列可以是索引列(在这种情况下与 b 一样)或常规列,例如我可能想找到行的索引('c' == 6)"
      【解决方案3】:

      你可以像这样使用np.where

      import pandas as pd
      import numpy as np
      df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                        columns = list('abc'), 
                        index=pd.Series([2,5], name='b'))
      print(df)
      #    a  b  c
      # b         
      # 2  1  2  3
      # 5  4  5  6
      print(np.where(df.index==5)[0])
      # [1]
      print(np.where(df['c']==6)[0])
      # [1]
      

      返回的值是一个数组,因为在一列中可能有多行具有特定索引或值。

      【讨论】:

      • np.where(df.index == 5)[0] 不同,pandas 有一个get_loc 功能,看起来更干净。 pandas.pydata.org/pandas-docs/stable/generated/…
      • @hlin117 - 您的评论应该是正确答案,请添加
      • 看起来比 pandas 方法更整洁、更易于理解。
      猜你喜欢
      • 2018-05-26
      • 2018-09-06
      • 1970-01-01
      • 2018-01-20
      • 2018-12-08
      • 2018-10-06
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多