将MultiIndex列合并到1级 [英] Merge MultiIndex columns together into 1 level
本文介绍了将MultiIndex列合并到1级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是另一个问题的一些数据:
Here's some data from another question:
date type value
1/1/2016 a 1
1/1/2016 b 2
1/1/2016 a 1
1/1/2016 b 4
1/2/2016 a 1
1/2/2016 b 1
运行以下代码行:
x = df.groupby(['date', 'type']).value.agg(['sum', 'max']).unstack()
x
应该看起来像这样:
sum max
type a b a b
date
1/1/2016 2 6 1 4
1/2/2016 1 1 1 1
我想合并上下两层的列以获取此信息:
I want to combine the columns on the upper and lower level to get this:
sum_a sum_b max_a max_b
date
1/1/2016 2 6 1 4
1/2/2016 1 1 1 1
有一种简单的方法吗?
推荐答案
这里有关于此的讨论:
共识似乎是:
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.
这篇关于将MultiIndex列合并到1级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文