与此帖子类似:efficient function to find harmonic mean across different pandas dataframes我有两个形状相同的 Pandas 数据框,我想找到每对元素的调和平均值 - 来自同一位置的每个数据框的一个元素。该帖子中给出的解决方案是使用面板,但现已弃用。
如果我这样做:
import pandas as pd
import numpy as np
from scipy.stats.mstats import hmean
df1 = pd.DataFrame(dict(x=np.random.randint(5, 10, 5), y=np.random.randint(1, 6, 5)))
df2 = pd.DataFrame(dict(x=np.random.randint(5, 10, 5), y=np.random.randint(1, 6, 5)))
dfs_dictionary = {'DF1':df1,'DF2':df2}
df=pd.concat(dfs_dictionary)
print(df)
x y
DF1 0 9 4
1 6 4
2 7 2
3 5 2
4 5 2
DF2 0 9 2
1 7 1
2 7 1
3 9 5
4 8 3
x = df.groupby(level = 1).apply(hmean, axis = None).reset_index()
print(x)
index 0
0 0 4.114286
1 1 2.564885
2 2 2.240000
3 3 3.956044
4 4 3.453237
我只得到一列值。为什么?我期望根据原始 df 有两列,一列用于 x 值的 hmean,一列用于 y 值的 hmean。我怎样才能实现我想做的事?
最佳答案
原因是您将 axis=None
传递给 hmean
,这会展平数据。请记住,当您执行groupby().apply()
时,参数是整个组,例如df.loc['DF1']
。只需删除 axis=None
:
x = df.groupby(level = 1).apply(hmean).reset_index()
你会得到:
index 0
0 0 [6.461538461538462, 3.0]
1 1 [5.833333333333333, 2.4000000000000004]
2 2 [8.0, 3.0]
3 3 [6.857142857142858, 2.4000000000000004]
4 4 [6.461538461538462, 2.857142857142857]
或者您可以使用agg
:
x = df.groupby(level = 1).agg({'x':hmean,'y':hmean})
并得到:
x y
0 6.461538 3.000000
1 5.833333 2.400000
2 8.000000 3.000000
3 6.857143 2.400000
4 6.461538 2.857143
如果您的列数不仅仅是 x,y
:
x = df.groupby(level=1).agg({c:hmean for c in df.columns})
关于python - 如何找到两个 Pandas 数据帧的元素调和平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65085102/