Skip to main content
 首页 » 编程设计

Python多行到一行

2025年05月04日17kevingrace

下面我有一个问题 - 我需要将多行 ID 转换为一行,并让不同的“输出”值变成二进制 1/0 的列,例如示例。

这是我的 table !

ID    Output      Timestamp 
1     out1        1501 
1     out2        1501 
1     out5        1501 
1     out9        1501 
2     out3        1603 
2     out4        1603 
2     out9        1603 

转化为:

ID     out1     out2     out3     out4     out5     out9      timestamp 
1      1        1        0        0        1        1         1501 
2      0        0        1        1        0        1         1603 

有人可以帮助我用 Python(最好是 Pandas)以灵活的方式做到这一点吗?我对此很陌生,多年来一直使用 SAS,因此非常感谢任何“过渡技巧”。

请您参考如下方法:

你可以使用一个枢轴:

pivoted = df.pivot('ID', 'Output', 'ID') 
pivoted.fillna(0, inplace=True) 
pivoted[pivoted > 0] = 1 
pd.merge(pivoted.reset_index(), df[['ID', 'Timestamp']].drop_duplicates(), left_on='ID', right_on='ID') 
pivoted 

结果:

 Output ID  out1    out2    out3    out4    out5    out9    Timestamp 
 0  1   1   1   0   0   1   1   1501 
 1  2   0   0   1   1   0   1   1603