Pandas计算多列数据中列减去的平均值

问题描述 投票:3回答:1

例如,我有如下数据帧

                       BTC               ETH
time(index)      high      low     high        low 
     1            3         1       4           2
     2            4         1       4           1

我希望index的意思是highlow之间的减号

每列如下

                      BTC                ETH
                      2.5                2.5

有没有办法使用pandas

python pandas
1个回答
4
投票

使用xs选择第二级MultiIndex,减去sub并获得mean

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添加to_frameT

df = s.to_frame().T
print (df)
   BTC  ETH
0  2.5  2.5

或者agg

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
© www.soinside.com 2019 - 2024. All rights reserved.