Python Pandas:使用条件从数据框中迭代提取列值

问题描述

我有两个数据框,每个数据框包含 3 列 df1(A,B,C) 和 df2(X,Y,Z)。我的目标是从 df1 中提取所有行,其中 A 和 X 之间的差异(每行中的 A,所有行中的 X)大于定义的阈值并且对于 B 来说相同Y 值, C 对 Z 值 - 然后对 df1 中的所有行进行迭代。我发现这很难用语言表达,所以希望这个例子和真值表能让它更清楚。示例输入(df1、df2)和输出(df3)。

thresh = 1

df1

Index  A    B    C
1      1    3    5   
2      4    2    6              
3      5    8    9

df2

Index  X    Y    Z
1      2.5  4.5  2   
2      3.5  5    6.5           
3      3.5  6    7 

df3

Index  A    B    C
1      1    3    5              
3      5    8    9

真值表:只有在所有测试(即 A 与任何 X、B 与任何 Y、C 和任何 Z 之间的差异)返回 true 时才应提取 df1 行。

是差异> thresh? 例如对于 df1 第 1 行(All True,因此此 df1 行存储在 df3 中,然后将对 df1 中的所有其他行重复此操作)

df1[A1],df2[X1]  df1[B1],df2[Y1]  df1[C1],df2[Z1] 
True             True             True    
df1[A1],df2[X2]  df1[B1],df2[Y2]  df1[C1],df2[Z2] 
True             True             True 
df1[A1],df2[X3]  df1[B1],df2[Y3]  df1[C1],df2[Z3] 
True             True             True 

解决方法

使用 np.repeatnp.tile 创建您的比较表

abc = np.repeat(df1.values,df2.shape[0],axis=0).reshape(df1.shape[0],-1)
xyz = np.tile(np.hstack(df2.values),df1.shape[0]).reshape(df1.shape[0],-1)

df3 = df1[np.all(np.abs(abc - xyz) > thres,axis=1)]
>>> df3
   A  B  C
1  1  3  5
3  5  8  9

用于测试组合

>>> df1
    A   B   C
1  A1  B1  C1
2  A2  B2  C2
3  A3  B3  C3

>>> df2
    X   Y   Z
1  X1  Y1  Z1
2  X2  Y2  Z2
3  X3  Y3  Z3

# abc = np.repeat(df1.values,-1)
# xyz = np.tile(np.hstack(df2.values),-1)

>>> abc
array([['A1','B1','C1','A1','C1'],['A2','B2','C2','A2','C2'],['A3','B3','C3','A3','C3']],dtype=object)

>>> xyz
array([['X1','Y1','Z1','X2','Y2','Z2','X3','Y3','Z3'],['X1','Z3']],dtype=object)

,

我不确定将此作为评论或答案,因为在这个问题中,准确地阐明您的意思和回答问题几乎是同一回事。

如果我正确理解你想要什么,我认为这会做到:

def check_row(row):
    return all(
                any(
                    abs(row[col1]-n2)> threshold
                    for n2 in df2[col2]
                    )
                for col1,col2 in 
                    zip(df1.columns,df2.columns)
        )

df1.loc[df1.apply(check_row,axis = 1)]

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...