df.iloc[i]
返回 df
的第 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