Pandas wide_to_long, the id variables need to uniquely identify each row

前端 未结 1 762
感动是毒
感动是毒 2021-01-22 05:54

Lets say I have a data frame like this

ID,Time1,Value1,Time2,Value2,Time3,Value3
1,2,1.1,3,1.2,4,1.3
1,5,2.1,6,2.2,7,2.3

And the expected dataf

相关标签:
1条回答
  • 2021-01-22 06:51

    Trick is use reset_index for column of unique values:

    df = (pd.wide_to_long(df.reset_index(), ['Time','Value'],i='index',j='value')
            .reset_index(drop=True)
            .sort_values(['ID', 'Time'])
            .dropna(how='any')
            )
    print (df)
       ID  Time  Value
    0   1     2    1.1
    2   1     3    1.2
    4   1     4    1.3
    1   1     5    2.1
    3   1     6    2.2
    5   1     7    2.3
    

    Detail:

    print (pd.wide_to_long(df.reset_index(), ['Time','Value'],i='index',j='value'))
                 ID  Time  Value
    index value                 
    0     1       1     2    1.1
    1     1       1     5    2.1
    0     2       1     3    1.2
    1     2       1     6    2.2
    0     3       1     4    1.3
    1     3       1     7    2.3
    
    0 讨论(0)
提交回复
热议问题