Python Pandas:获取列匹配特定值的行的索引
给定一个带有“BoolCol”列的DataFrame,我们希望findDataFrame的索引,其中“BoolCol”== True
我目前有迭代的方式来做到这一点,这是完美的:
for i in range(100,3000): if df.iloc[i]['BoolCol']== True: print i,df.iloc[i]['BoolCol'] 但这不是正确的pandas做的方式。 经过一番研究,我目前正在使用这个代码:
 df[df['BoolCol'] == True].index.tolist() 
这个给了我一个索引列表,但他们不匹配,当我检查他们做:
 df.iloc[i]['BoolCol'] 
其结果实际上是假的!
这将是正确的pandas方式做到这一点?
  df.iloc[i]返回df的ith行。  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来select行 : 
 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按序号索引select行: 
 In [113]: df.iloc[np.flatnonzero(df['BoolCol'])] Out[113]: BoolCol 10 True 40 True 50 True 
可以使用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 
虽然你并不总是需要一个匹配的索引,但incase如果你需要:
 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']