Pandas 通过取列之间的平均值合并两个数据帧

Pandas merge two dataframes by taking the mean between the columns

我正在使用 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 and aggregate 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