如何将Python DataFrame执行resample重采样后得到的多层级列转为扁平结构
Pandas重采样后多级列索引扁平化问题
当我使用如下语句对交易数据执行重采样操作时:
ohlc = trades.resample('1H').agg({'price': 'ohlc', 'volume': 'sum'})
得到的DataFrame的列是分层结构,按price、volume分组展示,示例如下:
price volume open high low close volume dtime 2021-06-30 22:00:00 34826.1 34923.4 34644.9 34875.8 68.884098 2021-06-30 23:00:00 34899.1 35208.8 34899.1 35046.2 83.506264 2021-07-01 00:00:00 35070.4 35070.4 34719.0 34761.5 81.766629
我希望将其转换为列扁平的普通DataFrame,这样就可以直接通过ohlc.open等方式访问对应列,预期效果如下:
open high low close volume dtime 2021-06-30 22:00:00 34826.1 34923.4 34644.9 34875.8 68.884098 2021-06-30 23:00:00 34899.1 35208.8 34899.1 35046.2 83.506264
我目前使用如下“暴力”代码实现该需求,但我认为应该有更简便优雅的实现方式,请问正确的操作方法是什么?
print(ohlc.price.open) # displays the "close" column but requires a redundant .price, .volume etc. hlc['open'] = ohlc.price.open ohlc['high'] = ohlc.price.high ohlc['low'] = ohlc.price.low ohlc['close'] = ohlc.price.close ohlc['volume1'] = ohlc.volume.volume ohlc = ohlc[['open', 'high', 'low', 'close', 'volume1']] ohlc['volume'] = ohlc.volume1 ohlc = ohlc[['open', 'high', 'low', 'close', 'volume']] print(ohlc.open) # now this displays the "open" column! The column label is missing, but I don't mind that.
解决方案
方法1:聚合阶段直接生成扁平结构(最推荐)
在重采样聚合时直接指定列名和对应计算规则,从根源避免生成多级索引:
ohlc = trades.resample('1H').agg( open=('price', 'first'), high=('price', 'max'), low=('price', 'min'), close=('price', 'last'), volume=('volume', 'sum') )
生成的DataFrame直接符合预期,可直接通过ohlc.open、ohlc.volume访问对应列。
方法2:对已生成的多级索引打平
如果已经生成了带多级列索引的ohlc对象,直接调用pandas内置方法删除第一层列索引即可:
ohlc = ohlc.droplevel(0, axis=1)
如果担心不同一级索引下有重名的二级列,也可以拼接两级索引作为新列名:
ohlc.columns = ['_'.join(col) for col in ohlc.columns]
内容的提问来源于stack exchange,提问作者Boaz
相关产品推荐
相关产品推荐

