pandas wide_to_long,id变量需要唯一地标识每一行 [英] Pandas wide_to_long, the id variables need to uniquely identify each row

查看:72
本文介绍了 pandas wide_to_long,id变量需要唯一地标识每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个像这样的数据框

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

预期的数据帧是这个

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在这种情况下就可以正常工作.

If the row has unique id, the pd.wide_to_long works perfectly in such case.

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不唯一,在这种情况下如何解决

but how to fix in such situation, if row's ID is not unique

推荐答案

使用技巧

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

详细信息:

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

这篇关于 pandas wide_to_long,id变量需要唯一地标识每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆