简体   繁体   中英

Pandas pivot/merge multiple columns into single, using column headers as values

I'm looking to combine three columns into a single column within a dataframe, using the column headers as the value for the new column. All three columns have a unique value of '1' where the other two just have NaN.

Originally I wanted to use pivot, but I suspect a merge operation would be easier? I'm just not sure how to go about it.

ie I need to turn

index     A       B        C        time      id
    0     1       NaN      NaN      4.42      1
    1     1       NaN      NaN      4.48      3
    2     1       NaN      NaN      5.45      2
    3     NaN     1        NaN      6.64      2
    4     NaN     1        NaN      7.49      1
    5     NaN     1        NaN      7.72      3
    6     NaN     NaN      1        8.13      1
    7     NaN     NaN      1        8.65      2
    8     NaN     NaN      1        9.07      3

into...

index     type  time    id
    0     A     4.42    1
    1     A     4.48    3
    2     A     5.45    2
    3     B     6.64    2
    4     B     7.49    1
    5     B     7.72    3
    6     C     8.13    1
    7     C     8.65    2
    8     C     9.07    3

Use:

  • set_index of columns for not reshaping
  • reshape all another columns by stack - NaNs rows are dropped
  • reorder_levels for change final ordering of columns
  • reset_index for columns from MultiIndex
  • remove column by drop
  • rename first column

df = (df.set_index(['time','id'])
       .stack()
       .reorder_levels([2,0,1])
       .reset_index(name='a')
       .drop('a', 1)
       .rename(columns={'level_0':'type'}))
print (df)
  type  time  id
0    A  4.42   1
1    A  4.48   3
2    A  5.45   2
3    B  6.64   2
4    B  7.49   1
5    B  7.72   3
6    C  8.13   1
7    C  8.65   2
8    C  9.07   3

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