【问题标题】:How to iterate through a pandas dataframe and find all rows with given value如何遍历熊猫数据框并查找具有给定值的所有行
【发布时间】:2022-01-17 21:57:23
【问题描述】:

如果我有一个包含数百行信息的 excel 文件,例如

| 0 |  1  |     2      |   3   |   4   |   5  |
-----------------------------------------------
| A | 212 | 10.10.1000 | 10:10 | 10.10 | 1.10 |
-----------------------------------------------
| B | 314 | 20.20.2000 | 20:20 | 20.20 | 2.20 |
-----------------------------------------------
| B | 314 | 20.20.2000 | 20:20 | 20.20 | 2.20 |

我想遍历它们并将包含特定数字的每一行保存在第二列中,我该怎么做? 我试过了,但没有用:

import pandas as pd

exsl = "excel file"
df = pd.read_excel(exsl)

value = 212

listOfMatches = []

for row in df:
  if value in row:
    listOfMatches.append(row)
    

所需的输出是一个包含所有行的列表,例如:

[[A, 212, 10.10.1000, 10:10, 10.10, 1.10],[...]]

【问题讨论】:

  • 不用循环,可以使用df.query("col_name == @value")
  • 你可以试试df[df[1] == 112].to_numpy().tolist()

标签: python excel pandas


【解决方案1】:

关于示例数据:

df= util.testing.makeMixedDataFrame()


    A   B   C   D
0   0.0     0.0     foo1    2009-01-01
1   1.0     1.0     foo2    2009-01-02
2   2.0     0.0     foo3    2009-01-05
3   3.0     1.0     foo4    2009-01-06
4   4.0     0.0     foo5    2009-01-07

过滤

df.query("B == 1")

    A   B   C   D
1   1.0     1.0     foo2    2009-01-02
3   3.0     1.0     foo4    2009-01-06

返回行列表

df.query("B == 1").values.tolist()

[[1.0, 1.0, 'foo2', Timestamp('2009-01-02 00:00:00')],
 [3.0, 1.0, 'foo4', Timestamp('2009-01-06 00:00:00')]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 2021-07-19
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多