代码之家  ›  专栏  ›  技术社区  ›  user96564

pandas从宽到长,id变量需要唯一地标识每一行

  •  2
  • user96564  · 技术社区  · 6 年前

    假设我有一个这样的数据帧

    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
    

    预期的数据帧是

    ID,Time,Value
    1,2,1.1
    1,3,1.2
    1,4,1.3
    1,5,2.1
    1,6,2.2
    1,7,2.3
    

    如果行具有唯一的id,则 pd.wide_to_long 在这种情况下非常有效。

    df = pd.wide_to_long(df, ['Time',Value],'ID','value', sep='', suffix='.+')\
        .reset_index()\
        .sort_values(['ID', 'Time'])\
        .drop('value', axis=1)\
        .dropna(how='any')
    

    但是在这种情况下,如果行的id不是唯一的,如何修复

    1 回复  |  直到 6 年前
        1
  •  3
  •   jezrael    6 年前

    诀窍是使用 reset_index 对于唯一值列:

    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
    

    细节 :

    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