gpt4 book ai didi

python-3.x - Pandas 通过取列之间的平均值来合并两个数据帧

转载 作者:行者123 更新时间:2023-12-04 12:46:41 24 4
gpt4 key购买 nike

我正在使用 Pandas DataFrames 并希望在其中两个之间取平均值。我正在寻找具有相同名称的列之间的平均值。
例如

df1

    time     x    y     z
0 1 1.25 2.5 0.75
1 2 2.75 2.5 3.00
2 3 1.50 2.5 1.25
3 4 3.00 2.5 3.50
4 5 0.50 2.5 2.25

df2
    time     x    y     z
0 2 0.75 2.5 1.75
1 3 3.00 2.5 3.00
2 4 1.25 2.5 0.25
3 5 3.50 2.5 2.00
4 6 2.25 2.5 2.25

我正在寻找的结果是

df3
    time     x    y     z
0 1 1.25 2.5 0.75
1 2 1.75 2.5 2.375
2 3 2.25 2.5 2.125
3 4 2.125 2.5 1.875
4 5 2.00 2.5 2.125
5 6 2.25 2.5 2.25

在 Pandas 中是否有一种简单的方法可以使用合并功能或类似功能来做到这一点?
我正在寻找一种无需指定列名称的方法。

最佳答案

我想你需要 concat + groupby 和聚合 mean :

df = pd.concat([df1, df2]).groupby('time', as_index=False).mean()
print (df)
time x y z
0 1 1.250 2.5 0.750
1 2 1.750 2.5 2.375
2 3 2.250 2.5 2.125
3 4 2.125 2.5 1.875
4 5 2.000 2.5 2.125
5 6 2.250 2.5 2.250

关于python-3.x - Pandas 通过取列之间的平均值来合并两个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45588650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com