这是我的question的后续行动。与透视表不同,是否可以将表展平,使其如下所示:
data = {'year': ['2016', '2016', '2015', '2014', '2013'],
'country':['uk', 'usa', 'fr','fr','uk'],
'sales': [10, 21, 20, 10,12],
'rep': ['john', 'john', 'claire', 'kyle','kyle']
}
pd.DataFrame(data).pivot_table(index='country', columns='year', values=['rep','sales'])
rep sales
year 2013 2014 2015 2016 2013 2014 2015 2016
country
fr None kyle claire None None 10 20 None
uk kyle None None john 12 None None 10
usa None None None john None None None 21
展平的桌子:
rep_2013 rep_2014 rep_2015 rep_2016 sales_2013 sales_2014 sales_2015 sales_2016
country
fr None kyle claire None None 10 20 None
uk kyle None None john 12 None None 10
usa None None None john None None None 21
最佳答案
见collapse a pandas MultiIndex
解决方案
df.columns = df.columns.to_series().str.join('_')
关于python - 展平 Pandas 数据透视表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39273441/