pandas 展平熊猫数据透视表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39273441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:56:04  来源:igfitidea点击:

Flatten pandas pivot table

pythonpandas

提问by DougKruger

This is a follow up of my question. Rather than a pivot table, is it possible to flatten table to look like the following:

这是我的问题的后续行动。是否可以将表格展平为如下所示,而不是数据透视表:

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

Flattened table:

压平表:

        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

回答by piRSquared

see collapse a pandas MultiIndex

请参阅折叠Pandas MultiIndex

Solution

解决方案

df.columns = df.columns.to_series().str.join('_')

回答by SerialDev

Try this:

尝试这个:

df.columns = df.columns.get_level_values(0)

followed by:

其次是:

df.columns = [' '.join(col).strip() for col in df.columns.values]

This should flatten your multi-index

这应该会使您的多索引变平