pandas pivot_table列名称 [英] pandas pivot_table column names
本文介绍了 pandas pivot_table列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于这样的数据框:
d = {'id': [1,1,1,2,2], 'Month':[1,2,3,1,3],'Value':[12,23,15,45,34], 'Cost':[124,214,1234,1324,234]}
df = pd.DataFrame(d)
Cost Month Value id
0 124 1 12 1
1 214 2 23 1
2 1234 3 15 1
3 1324 1 45 2
4 234 3 34 2
我将数据透视表应用于的
to which I apply pivot_table
df2 = pd.pivot_table(df,
values=['Value','Cost'],
index=['id'],
columns=['Month'],
aggfunc=np.sum,
fill_value=0)
获取df2:
Cost Value
Month 1 2 3 1 2 3
id
1 124 214 1234 12 23 15
2 1324 0 234 45 0 34
是否有一种简单的方法来格式化结果数据框列名,如
is there an easy way to format resulting dataframe column names like
id Cost1 Cost2 Cost3 Value1 Value2 Value3
1 124 214 1234 12 23 15
2 1324 0 234 45 0 34
如果我这样做:
df2.columns =[s1 + str(s2) for (s1,s2) in df2.columns.tolist()]
我得到:
Cost1 Cost2 Cost3 Value1 Value2 Value3
id
1 124 214 1234 12 23 15
2 1324 0 234 45 0 34
如何摆脱多余的关卡?
谢谢!
推荐答案
使用@chrisb的答案中的线索,这确实给了我我想要的东西:
Using clues from @chrisb's answer, this gave me exactly what I was after:
df2.reset_index(inplace=True)
给出:
id Cost1 Cost2 Cost3 Value1 Value2 Value3
1 124 214 1234 12 23 15
2 1324 0 234 45 0 34
,如果有多个索引列,请此帖子说明得很好.只是为了完整,这是怎么做的:
and in case of multiple index columns, this post explains it well. just to be complete, here is how:
df2.columns = [' '.join(col).strip() for col in df2.columns.values]
这篇关于 pandas pivot_table列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文