在不同的 pandas 数据帧之间找到调和平均值的有效函数 [英] efficient function to find harmonic mean across different pandas dataframes
问题描述
我有几个形状/类型相同的数据框,但数值略有不同.我可以通过以下方式轻松生成具有所有输入数据帧平均值的新数据帧:
I have several dataframes with identical shape/types, but slightly different numeric values. I can easily produce a new dataframe with the mean of all input dataframes via:
df = pd.concat([input_dataframes])
df = df.groupby(df.index).mean()
我想对调和平均值(可能是 scipy.stats.hmean 函数)做同样的事情.我尝试使用:
I want to do the same with harmonic mean (probably the scipy.stats.hmean function). I have attempted to do this using:
.groupby(df.index).apply(scipy.stats.hmean)
但这改变了数据帧的结构.有没有更好的方法来做到这一点,还是我需要使用更冗长的/手动实现?
But this alters the structure of the dataframe. Is there a better way to do this, or do I need to use a more lengthly/manual implementation?
举例说明:
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
推荐答案
创建一个 Pandas Panel,并在 'item' 轴上应用调和平均函数.
Create a pandas Panel, and apply the harmonic mean function over the 'item' axis.
以您的数据帧 df1
和 df2
为例:
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)
产量:
'a' 'b' 'c'
'x' 1.333333 1.333333 2.666667
'y' 2.400000 2.400000 4.800000
'z' 3.428571 3.428571 6.857143
这篇关于在不同的 pandas 数据帧之间找到调和平均值的有效函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!