Python 计算多列数据中列减号的平均值
例如,我的dataframe如下所示Python 计算多列数据中列减号的平均值,python,pandas,Python,Pandas,例如,我的dataframe如下所示 BTC ETH time(index) high low high low 1 3 1 4 2 2 4 1 4 1 我要的是索引,在高和低 按下面的每一列
BTC ETH
time(index) high low high low
1 3 1 4 2
2 4 1 4 1
我要的是索引
,在高
和低
按下面的每一列
BTC ETH
2.5 2.5
有没有办法使用熊猫呢?用于按第二级的多索引进行选择
,减去并获得平均值
:
s = df.xs('high', axis=1, level=1).sub(df.xs('low', axis=1, level=1)).mean()
print (s)
BTC 2.5
ETH 2.5
dtype: float64
如果需要一行DataFrame
添加和:
或:
详细信息:
print (df.xs('high', axis=1, level=1))
BTC ETH
1 3 4
2 4 4
print (df.xs('high', axis=1, level=1).sub(df.xs('low', axis=1, level=1)))
BTC ETH
1 2 2
2 3 3
df = df.xs('high', axis=1, level=1).sub(df.xs('low', axis=1, level=1)).agg(['mean'])
print (df)
BTC ETH
mean 2.5 2.5
print (df.xs('high', axis=1, level=1))
BTC ETH
1 3 4
2 4 4
print (df.xs('high', axis=1, level=1).sub(df.xs('low', axis=1, level=1)))
BTC ETH
1 2 2
2 3 3