在不同的熊猫数据帧之间找到调和平均值的有效函数

Bry*_*ipp 4 python scipy pandas

我有几个具有相同形状/类型但数值略有不同的数据框。我可以通过以下方式轻松生成具有所有输入数据帧平均值的新数据帧:

df = pd.concat([input_dataframes])
df = df.groupby(df.index).mean()
Run Code Online (Sandbox Code Playgroud)

我想对调和平均值(可能是 scipy.stats.hmean 函数)做同样的事情。我尝试使用以下方法执行此操作:

.groupby(df.index).apply(scipy.stats.hmean)
Run Code Online (Sandbox Code Playgroud)

但这会改变数据帧的结构。有没有更好的方法来做到这一点,或者我是否需要使用更长的/手动实现?

为了显示 :

df_input1:
   'a' 'b' 'c'
'x' 1   1   2 
'y' 2   2   4 
'z' 3   3   6

df_input2:
   'a' 'b' 'c'
'x' 2   2   4 
'y' 3   3   6 
'z' 4   4   8

desired output (but w/ hmean):
   'a'  'b'  'c'
'x' 1.5  1.5  3 
'y' 2.5  2.5  5 
'z' 3.5  3.5  7
Run Code Online (Sandbox Code Playgroud)

vmg*_*vmg 5

Create a pandas Panel, and apply the harmonic mean function over the 'item' axis.

Example with your dataframes df1 and df2:

import pandas as pd
from scipy import stats

d = {'1':df1,'2':df2}
pan = pd.Panel(d)
pan.apply(axis='items',func=stats.hmean)
Run Code Online (Sandbox Code Playgroud)

yields:

        'a'         'b'         'c'
'x'     1.333333    1.333333    2.666667
'y'     2.400000    2.400000    4.800000
'z'     3.428571    3.428571    6.857143
Run Code Online (Sandbox Code Playgroud)