给定一个带有“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']
结果实际上是假的!!
这是正确的熊猫方式吗?
2 Answers
df.iloc[i]
返回df
的ith
行 .i
不引用索引标签,i
是基于0的索引 .相比之下, the attribute index returns actual index labels ,而不是数字行索引:
或等效地,
通过使用带有“异常”索引的DataFrame,您可以非常清楚地看到差异:
If you want to use the index ,
then you can select the rows using loc instead of iloc :
注意 loc can also accept boolean arrays :
If you have a boolean array, mask, and need ordinal index values, you can compute them using np.flatnonzero :
使用
df.iloc
按顺序索引选择行:可以使用numpy where()函数完成:
虽然您并不总是需要匹配索引,但如果您需要,请填写: