您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python Pandas:获取列匹配特定值的行的索引

Python Pandas:获取列匹配特定值的行的索引

df.iloc[i]返回的ithdfi不引用索引标签i是基于0的索引。

相反, ,而不是数字的行索引:

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')

In [58]: df.loc[idx]
Out[58]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

注意, :

In [55]: df.loc[df['BoolCol']]
Out[55]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

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 2022/1/1 18:28:14 有189人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶