Merge MultiIndex columns together into 1 level [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-05 04:04:23
greg_data

There's discussion of this here:

Python Pandas - How to flatten a hierarchical index in columns

And the consensus seems to be:

x.columns = ['_'.join(col) for col in x.columns.values]
print(x)
          sum_a  sum_b  max_a  max_b
date                                
1/1/2016      2      6      1      4
1/2/2016      1      1      1      1

Would be nice if there was an inbuilt method for this, but there doesn't seem to be.

Very similar solution to the above using zip:

x.columns = [x + '_' + i for x, i in zip(x.columns.get_level_values(0), x.columns.get_level_values(1))]
x
          sum_a  sum_b  max_a  max_b
date                                
1/1/2016      2      6      1      4
1/2/2016      1      1      1      1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!