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

作者:貔貅 时间:2023-11-01 06:37:42 

给定一个带有列"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 获取列匹配特定值的行的索引问题

参考文献

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

总结

以上所述是小编给大家介绍的Python Pandas 获取列匹配特定值的行的索引问题,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

来源:https://vimsky.com/article/3713.html

标签:python,pandas,匹配
0
投稿

猜你喜欢

  • 详解Go语言中的数据库操作

    2024-01-15 19:30:23
  • python多线程方法详解

    2023-10-16 02:46:31
  • getdata table表格数据join mysql方法

    2024-01-25 17:55:08
  • 详解Python的Django框架中的模版相关知识

    2023-04-22 02:46:25
  • vue3中cookie的详细使用过程

    2024-04-30 08:45:05
  • python数字图像处理之骨架提取与分水岭算法

    2023-03-07 15:59:50
  • python中字典dict排序sorted的实现

    2023-02-20 13:21:45
  • vue简单的二维数组循环嵌套方式

    2024-04-27 16:09:56
  • Ubuntu中更改MySQL数据库文件目录的方法

    2024-01-15 06:39:18
  • Python判断变量是否已经定义的方法

    2023-08-01 07:14:01
  • python基于scrapy爬取京东笔记本电脑数据并进行简单处理和分析

    2023-08-05 03:18:06
  • mysql下mysqladmin日常管理命令总结(必看篇)

    2024-01-16 23:35:55
  • Python爬虫基于lxml解决数据编码乱码问题

    2021-09-11 23:48:44
  • JavaScript中两个字符串的匹配

    2023-08-08 00:46:01
  • python使用梯度下降和牛顿法寻找Rosenbrock函数最小值实例

    2022-09-10 20:01:20
  • Golang嵌入资源文件实现步骤详解

    2023-06-21 08:52:36
  • 使用numpy.ndarray添加元素

    2022-10-31 06:12:15
  • python利用xlsxwriter模块 操作 Excel

    2023-02-11 00:43:02
  • Python选课系统开发程序

    2023-07-21 00:25:03
  • 利用Python生成随机验证码详解

    2021-10-04 19:55:50
  • asp之家 网络编程 m.aspxhome.com