我有一个独特的要求,我需要两个数据帧的公共列(每行)。
我想不出这样做的pythonic方法。我知道我可以遍历两个数据帧并找到公共列,然后获得密钥匹配的行的平均值。
假设我有以下数据框: DF1:
Key A B C D E
K1 2 3 4 5 8
K2 2 3 4 5 8
K3 2 3 4 5 8
K4 2 3 4 5 8
DF2:
Key A B C D
K1 4 7 4 7
K2 4 7 4 7
K3 4 7 4 7
K4 4 7 4 7
结果DF应该是两个DF的平均值,每个列的每个列都与Key匹配。 ResultDF:
Key A B C D
K1 3 5 4 6
K2 3 5 4 6
K3 3 5 4 6
K4 3 5 4 6
我知道我应该把示例代码放在这里,但我想不出任何实现此目的的逻辑。
答案 0 :(得分:2)
使用DataFrame.add
作为索引使用Key
:
df1.set_index('Key').add(df2.set_index('Key')).dropna(axis=1) / 2
A B C D
Key
K1 3 5 4 6
K2 3 5 4 6
K3 3 5 4 6
K4 3 5 4 6
替代concat
+ groupby
。
pd.concat([df1, df2], axis=0).dropna(axis=1).groupby('Key').mean()
A B C D
Key
K1 3 5 4 6
K2 3 5 4 6
K3 3 5 4 6
K4 3 5 4 6
答案 1 :(得分:1)
尝试将数据框添加到一起,然后使用pandas apply
函数,然后在其中添加lambda
,然后将x
除以2:
import pandas as pd
df1 = pd.DataFrame({'A': [2,2]})
df2 = pd.DataFrame({'A': [4,4]})
print((df1+df2).apply(lambda x: x/2))
输出:
A
0 3.0
1 3.0
注意:这只是一个虚拟数据框