pandas dataframe reshaping/stacking of multiple value variables into seperate columns

前端 未结 3 850
小蘑菇
小蘑菇 2020-12-17 06:01

Hi I\'m trying to reshape a data frame in a certain way.

this is the data frame I have,

         des1 des2 des3 interval1 interval2 interval3
value           


        
3条回答
  •  生来不讨喜
    2020-12-17 06:35

    I think the solution provided by CT Zhu is very genius. But you also can reshape this step by step (maybe this is the common way).

     d = {'des1' : ['', 'a', 'd', 'g'],
         'des2' : ['', 'b', 'e', 'h'],
         'des3' : ['', 'c', 'f', 'i'],
         'interval1' : ['', '##1', '##4', '##7'],
         'interval2' : ['', '##2', '##5', '##6'],
         'interval3' : ['', '##3', '##6', '##9']}
    
    df = pd.DataFrame(d, index=['value', 'aaa', 'bbb', 'ccc'], 
                      columns=['des1', 'des2', 'des3', 'interval1', 'interval2', 'interval3'])
    
    nd = {'des' : [''] + df.iloc[1, 0:3].tolist() + df.iloc[2, 0:3].tolist() + df.iloc[3, 0:3].tolist(),
          'interval' : ['']+ df.iloc[1, 3:6].tolist() + df.iloc[2, 3:6].tolist() + df.iloc[3, 3:6].tolist()}
    
    ndf = pd.DataFrame(nd, index=['value', 'aaa', 'aaa', 'aaa', 'bbb', 'bbb', 'bbb', 'ccc', 'ccc', 'ccc'], columns=['des', 'interval'])
    

提交回复
热议问题