【问题标题】:Pythonic way to iterate over a Dataframe when column row value matches condition当列行值匹配条件时迭代数据框的 Pythonic 方法
【发布时间】:2020-12-18 04:46:15
【问题描述】:

我想绘制一个密度图,需要从数据中提取两个值用作坐标,第三个值将作为密度值。我有一个要读取的文本文件,当一个行/列值与某个条件匹配时,我想保存该行的另外两个值。我有一些适用于其中一种条件的东西,但它将行值保存在嵌套列表中,我想知道是否有更 Pythonic 的方式来执行此操作,因为我认为以后可能更容易绘制。

数据:

Accum   EdgeThr NumberOfBlobs   durationMin Vol Perom   X   Y
50  0   0   0.03    0   0   0   0
50  2   0   0.03    0   0   0   0
50  4   0   0.03    0   0   0   0
50  6   0   0.03    0   0   0   0
50  8   2   0.03    27.833133599054975  0.0 1032.0  928.0
50  10  2   0.03    27.833133599054975  0.0 1032.0  928.0
46  30  2   0.17    27.833133599054975  0.0 968.0   962.0
46  32  2   0.17    27.833133599054975  0.0 1028.0  1020.0
46  34  2   0.17    27.833133599054975  0.0 978.0   1122.0
46  36  2   0.17    27.833133599054975  0.0 1000.0  1080.0
46  38  2   0.18    27.833133599054975  0.0 1010.0  1062.0

代码:

import pandas as pd

# load data as a pandas dataframe
df = pd.read_csv('dummy.txt', sep='\t', lineterminator='\r')

# to find the rows matching one condition ==2
blob2 = []
for index, row in df.iterrows():
    temp = [row['Accum'], row['EdgeThr']]
    if row['NumberOfBlobs']==2:
        blob2.append(temp)
        print(index, row['Accum'], row['EdgeThr'], row['NumberOfBlobs'])
print(blob2)

【问题讨论】:

  • 嗨@JohanC 你能把它作为答案发给我吗?

标签: python pandas dataframe loops indexing


【解决方案1】:

df[df['NumberOfBlobs'] == 2] 将选择所有满足条件的行。

df[df['NumberOfBlobs'] == 2][['Accum', 'EdgeThr']] 将选择这两列。

这是一个例子:

import pandas as pd
import numpy as np

N = 10
df = pd.DataFrame({'Accum': np.random.randint(40, 50, N), 'EdgeThr': np.random.randint(0, 50, N),
                   'NumberOfBlobs': np.random.randint(0, 2, N) * 2})
blobs2 = df[df['NumberOfBlobs'] == 2][['Accum', 'EdgeThr']]

df 的示例:

   Accum  EdgeThr  NumberOfBlobs
0     42       44              2
1     47       32              0
2     45        9              2
3     48       15              2
4     44        6              0
5     42       24              0
6     46       20              0
7     46        9              0
8     40       36              0
9     41        3              0

blobs2:

   Accum  EdgeThr
0     42       44
2     45        9
3     48       15

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2021-08-02
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 2016-12-29
    • 1970-01-01
    相关资源
    最近更新 更多