简体   繁体   中英

How to rename the column names post flattening

This is

    Date      Group   Value   Duration
2018-01-01      A      20       30
2018-02-01      A      10       60
2018-03-01      A      25       88    
2018-01-01      B      15      180
2018-02-01      B      30      210
2018-03-01      B      25      238    

I want to pivot the above df

My Approach:

 df_pivot = dealer_f.pivot_table(index='Group',columns='Date',fill_value=0)
 df_pivot.columns = dealer_f_pivot.columns.map('_'.join)
 ff_pivot = dealer_f_pivot.reset_index()

I am getting an error as TypeError: sequence item 1: expected str instance, int found

If I simply follow reset_index then I get the column names as ('Value',2018-01-01),('Value',2018-02-10) etc.

I want to flatten the columns so that my output looks like below

df_pivot.columns.tolist()
['2018-01-01_Value','2018-02-01_Value',.....'2018-01-01_Duration',...]

Any clue? Or where I am missing?

Use:

 df_pivot.columns = [f'{b}_{a}' for a, b in df_pivot.columns]

Or:

df_pivot.columns = [f'{b.strftime("%Y-%m-%d")}_{a}' for a, b in df_pivot.columns]
df_pivot = df_pivot.reset_index()
print (df_pivot)
  Group  2018-01-01_Duration  2018-02-01_Duration  2018-03-01_Duration  \
0     A                   30                   60                   88   
1     B                  180                  210                  238   

   2018-01-01_Value  2018-02-01_Value  2018-03-01_Value  
0                20                10                25  
1                15                30                25  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM