如何在展平后重命名列名

这是

    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

我的方法:

 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',...]

有什么线索吗?还是我想念的地方?

评论
之冰巧
之冰巧

采用:

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

要么:

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  
点赞
评论