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

yipeiwu_com5年前Python基础

给定一个带有列"BoolCol"的DataFrame,如何找到满足条件"BoolCol" == True的DataFrame的索引

目前有迭代的方式来做到这一点:

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

其结果实际上是False!

如何使用正确的 Pandas 方式做到这一点?

最佳解决方法

df.iloc[i]返回df的第i行。 i不引用索引标签,i是从0开始的索引。

相反,属性index返回实际的索引标签,而不是数字row-indices:

df.index[df['BoolCol'] == True].tolist()

或者等同地,

df.index[df['BoolCol']].tolist()

通过使用带有"unusual"索引的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
python pandas

参考文献

Python Pandas:  Get index of rows which column matches certain value

总结

以上所述是小编给大家介绍的Python Pandas 获取列匹配特定值的行的索引问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

对python实时得到鼠标位置的示例讲解

对python实时得到鼠标位置的示例讲解

如下所示: #先下载pyautogui库,pip install pyautogui import os,time import pyautogui as pag try: wh...

python实现名片管理器的示例代码

编写程序,完成“名片管理器”项目 需要完成的基本功能: 添加名片 删除名片 修改名片 查询名片 退出系统 程序运行后,除非选择退出系统,否则重复执行功能 mi...

Python中标准模块importlib详解

1 模块简介 Python提供了importlib包作为标准库的一部分。目的就是提供Python中import语句的实现(以及__import__函数)。另外,importlib允许程序...

TensorFlow搭建神经网络最佳实践

一、TensorFLow完整样例 在MNIST数据集上,搭建一个简单神经网络结构,一个包含ReLU单元的非线性化处理的两层神经网络。在训练神经网络的时候,使用带指数衰减的学习率设置、使用...

python 域名分析工具实现代码

代码如下: 复制代码 代码如下:import sys, urllib import datetime,time def getDate(): strday=datetime.dateti...