Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

python - Flatten pandas pivot table

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

see collapse a pandas MultiIndex

Solution

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...