Python Pandas:获取列匹配某个值的行的索引

新手上路,请多包涵

给定一个带有“BoolCol”列的DataFrame,我们想要找到DataFrame的索引,其中“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']

结果居然是假的!!

哪一种是正确的熊猫方式来做到这一点?

原文由 I want badges 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 771
2 个回答

df.iloc[i] 返回 ithdfi 不引用索引标签, 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

原文由 unutbu 发布,翻译遵循 CC BY-SA 4.0 许可协议

可以使用 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']

原文由 Surya 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题