给定一个带有“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']
结果居然是假的!!
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 选择行:
In [58]: df.loc[idx]
Out[58]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
注意 loc 也可以接受 bool 数组:
In [55]: df.loc[df['BoolCol']]
Out[55]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
如果您有一个 bool 数组,mask,并且需要序数索引值,您可以使用 np.flatnonzero 计算它们: p>
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
关于Python Pandas : Get index of rows where column matches certain value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21800169/