例如,我有如下数据帧
BTC ETH
time(index) high low high low
1 3 1 4 2
2 4 1 4 1
我希望index
的意思是high
和low
之间的减号
每列如下
BTC ETH
2.5 2.5
有没有办法使用pandas
?
使用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
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