简体   繁体   中英

Pivot table and merge column with headers

I have DataFrame as below:

 Ranges Relative_17-Sep Relative_17-Oct Relative_17-Nov
  <=20%  0.65            0.36            0.29
  >20%   99.35           99.64           99.71

I am trying to find a way to convert this to :

"Sep17<=20%" "Sep17>20%"   "Oct17<=20%" "Oct17>20%" "Nov17<=20%" "Nov17>20%"
 0.65          99.35        0.36            99.64     0.29        99.71

Any help in this.

Thanks

Option 1
melt

v = df.melt('Ranges')

df = pd.DataFrame(
    v['value'].values, 
    index=v['variable'].str.split('_').str[-1] + v['Ranges']
).T

df
   17-Sep<=20%  17-Sep>20%  17-Oct<=20%  17-Oct>20%  17-Nov<=20%  17-Nov>20%
0         0.65       99.35         0.36       99.64         0.29       99.71

Option 2
Modify df.columns , followed by a stack ing operation.

df.columns = df.columns.str.split('_').str[-1]
v = df.set_index('Ranges').stack()

df = pd.DataFrame(
    v.values, 
    index=v.index.get_level_values(1) + v.index.get_level_values(0)
).T

df
   17-Sep<=20%  17-Oct<=20%  17-Nov<=20%  17-Sep>20%  17-Oct>20%  17-Nov>20%
0         0.65         0.36         0.29       99.35       99.64       99.71

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