【问题标题】:Python Pandas: Get index of rows which column matches certain valuePython Pandas:获取与特定值匹配的行的索引
【发布时间】:2014-03-15 01:01:10
【问题描述】:

给定一个带有“BoolCol”列的 DataFrame,我们想要找到 DataFrame 的索引,其中“BoolCol”的值 == True

我目前有迭代的方法,效果很好:

for i in range(100,3000):
    if df.iloc[i]['BoolCol']== True:
         print i,df.iloc[i]['BoolCol']

但这不是熊猫的正确做法。 经过一番研究,我目前正在使用此代码:

df[df['BoolCol'] == True].index.tolist()

这个给了我一个索引列表,但是当我检查它们时它们不匹配:

df.iloc[i]['BoolCol']

结果居然是假的!!

Pandas 的正确做法是什么?

【问题讨论】:

    标签: python indexing pandas


    【解决方案1】:

    df.iloc[i] 返回dfith 行。 i 不引用索引标签,i 是从 0 开始的索引。

    相比之下,index 属性返回实际的索引标签,而不是数字行索引:

    df.index[df['BoolCol'] == True].tolist()
    

    或等价的,

    df.index[df['BoolCol']].tolist()
    

    你可以通过使用 DataFrame 非常清楚地看到差异 不等于行的数字位置的非默认索引:

    df = pd.DataFrame({'BoolCol': [True, False, False, True, True]},
           index=[10,20,30,40,50])
    
    In [53]: df
    Out[53]: 
       BoolCol
    10    True
    20   False
    30   False
    40    True
    50    True
    
    [5 rows x 1 columns]
    
    In [54]: df.index[df['BoolCol']].tolist()
    Out[54]: [10, 40, 50]
    

    如果要使用索引

    In [56]: idx = df.index[df['BoolCol']]
    
    In [57]: idx
    Out[57]: Int64Index([10, 40, 50], dtype='int64')
    

    然后您可以使用loc 而不是iloc 选择行

    In [58]: df.loc[idx]
    Out[58]: 
       BoolCol
    10    True
    40    True
    50    True
    
    [3 rows x 1 columns]
    

    请注意,loc 也可以接受布尔数组

    In [55]: df.loc[df['BoolCol']]
    Out[55]: 
       BoolCol
    10    True
    40    True
    50    True
    
    [3 rows x 1 columns]
    

    如果您有一个布尔数组 mask,并且需要序数索引值,您可以使用 np.flatnonzero 计算它们

    In [110]: np.flatnonzero(df['BoolCol'])
    Out[112]: array([0, 3, 4])
    

    使用df.iloc按序号索引选择行:

    In [113]: df.iloc[np.flatnonzero(df['BoolCol'])]
    Out[113]: 
       BoolCol
    10    True
    40    True
    50    True
    

    【讨论】:

    • 另一种方法是df.query('BoolCol')
    • 我知道这很旧,但我想知道是否有一种简单的方法可以从查询中获取基于 0 的索引号。我需要 iloc 数字,因为我想在满足特定条件的行之前和之后选择一些行。所以我的计划是让行的 0 索引满足条件,然后创建切片以在 iloc() 中使用。我唯一看到的是get_loc,但它不能带数组。
    • @sheridp:如果您有一个布尔掩码,您可以使用np.flatnonzero 找到maskTrue 的序数索引。我已经编辑了上面的帖子以说明我的意思。
    • 您的建议 indices = np.flatnonzero(df[col_name] == category_name) 让我得到了问题标题所要求的准确信息,这在互联网上很难找到。
    • 如果只想返回索引,df[dftest].index 的开销是多少?这是否会创建一个中间数据帧(其数据可能是千兆字节)。那么dftest呢?这不是也分配了一个非常大的中间对象,其中返回的索引可能非常小,甚至是空的。这些是否使用惰性视图神奇地优化了。如果没有,那么肯定有一种有效的方法。
    【解决方案2】:

    可以使用 numpy where() 函数来完成:

    import pandas as pd
    import numpy as np
    
    In [716]: df = pd.DataFrame({"gene_name": ['SLC45A1', 'NECAP2', 'CLIC4', 'ADC', 'AGBL4'] , "BoolCol": [False, True, False, True, True] },
           index=list("abcde"))
    
    In [717]: df
    Out[717]: 
      BoolCol gene_name
    a   False   SLC45A1
    b    True    NECAP2
    c   False     CLIC4
    d    True       ADC
    e    True     AGBL4
    
    In [718]: np.where(df["BoolCol"] == True)
    Out[718]: (array([1, 3, 4]),)
    
    In [719]: select_indices = list(np.where(df["BoolCol"] == True)[0])
    
    In [720]: df.iloc[select_indices]
    Out[720]: 
      BoolCol gene_name
    b    True    NECAP2
    d    True       ADC
    e    True     AGBL4
    

    虽然你并不总是需要索引来匹配,但如果你需要的话:

    In [796]: df.iloc[select_indices].index
    Out[796]: Index([u'b', u'd', u'e'], dtype='object')
    
    In [797]: df.iloc[select_indices].index.tolist()
    Out[797]: ['b', 'd', 'e']
    

    【讨论】:

      【解决方案3】:

      首先你可以在目标列是bool时查看query(PS:使用方法请查看link

      df.query('BoolCol')
      Out[123]: 
          BoolCol
      10     True
      40     True
      50     True
      

      通过布尔列过滤原始 df 后,我们可以选择索引。

      df=df.query('BoolCol')
      df.index
      Out[125]: Int64Index([10, 40, 50], dtype='int64')
      

      pandas 也有nonzero,我们只需选择True 行的位置 并使用它对DataFrameindex 进行切片

      df.index[df.BoolCol.nonzero()[0]]
      Out[128]: Int64Index([10, 40, 50], dtype='int64')
      

      【讨论】:

        【解决方案4】:

        简单的方法是在过滤之前重置DataFrame的索引:

        df_reset = df.reset_index()
        df_reset[df_reset['BoolCol']].index.tolist()
        

        有点老套,但很快!

        【讨论】:

          【解决方案5】:

          我扩展了这个问题,即如何获取所有匹配值的rowcolumnvalue

          解决办法:

          import pandas as pd
          import numpy as np
          
          
          def search_coordinate(df_data: pd.DataFrame, search_set: set) -> list:
              nda_values = df_data.values
              tuple_index = np.where(np.isin(nda_values, [e for e in search_set]))
              return [(row, col, nda_values[row][col]) for row, col in zip(tuple_index[0], tuple_index[1])]
          
          
          if __name__ == '__main__':
              test_datas = [['cat', 'dog', ''],
                            ['goldfish', '', 'kitten'],
                            ['Puppy', 'hamster', 'mouse']
                            ]
              df_data = pd.DataFrame(test_datas)
              print(df_data)
              result_list = search_coordinate(df_data, {'dog', 'Puppy'})
              print(f"\n\n{'row':<4} {'col':<4} {'name':>10}")
              [print(f"{row:<4} {col:<4} {name:>10}") for row, col, name in result_list]
          

          输出:

                    0        1       2
          0       cat      dog        
          1  goldfish           kitten
          2     Puppy  hamster   mouse
          
          
          row  col        name
          0    1           dog
          2    0         Puppy
          

          【讨论】:

            【解决方案6】:

            如果您只想使用一次数据框对象,请使用:

            df['BoolCol'].loc[lambda x: x==True].index
            

            【讨论】:

              【解决方案7】:

              对于我们感兴趣的已知索引候选,不检查整个列的更快方法可以这样完成:

              np.array(index_slice)[np.where(df.loc[index_slice]['column_name'] >= threshold)[0]]
              

              全面比较:

              import pandas as pd
              import numpy as np
              
              index_slice = list(range(50,150)) # know index location for our inteterest
              data = np.zeros(10000)
              data[(index_slice)] = np.random.random(len(index_slice))
              
              df = pd.DataFrame(
                  {'column_name': data},
              )
              
              threshold = 0.5
              
              
              %%timeit
              np.array(index_slice)[np.where(df.loc[index_slice]['column_name'] >= threshold)[0]]
              # 600 µs ± 1.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
              
              %%timeit
              [i for i in index_slice if i in df.index[df['column_name'] >= threshold].tolist()]
              # 22.5 ms ± 29.1 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
              

              它的工作方式是这样的:

              # generate Boolean satisfy condition only in sliced column
              df.loc[index_slice]['column_name'] >= threshold
              
              # convert Boolean to index, but start from 0 and increment by 1
              np.where(...)[0]
              
              # list of index to be sliced
              np.array(index_slice)[...]
              

              注意: 需要注意的是,np.array(index_slice) 不能被df.index 替换,因为np.where(...)[0] 索引start from 0 and increment by 1,但是你可以做类似df.index[index_slice] 的东西。而且我认为如果你只用少量的行做一次,这不值得麻烦。

              【讨论】:

                猜你喜欢
                • 2023-02-01
                • 2016-12-07
                • 2018-01-20
                • 2018-10-01
                • 1970-01-01
                • 1970-01-01
                • 2019-08-11
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多