在Python中将垂直系列重塑为水平

时间:2018-12-11 02:14:18

标签: python python-3.x pandas

我有一个简单的系列数据,看起来像:

  id    
100241  Issue 1
100241  Issue 2
100241  Issue 3
100242  Issue 1
100242  Issue 2
100242  Issue 3

我的目标是将其重塑为水平格式,每个id及其相关问题均保存一行,并保存在excel中,看起来像

 id         
100241  Issue 1 Issue 2 Issue 3
100242  Issue 1 Issue 2 Issue 3

我是Python的新手,不确定如何使用Python实现它?谢谢。

2 个答案:

答案 0 :(得分:5)

您可以将一级附加到索引和unstack

counts = series.groupby(level=0).cumcount()
series.to_frame().set_index(counts, append=True).iloc[:,0].unstack()

              0        1        2
id                               
100241  Issue 1  Issue 2  Issue 3
100242  Issue 1  Issue 2  Issue 3

答案 1 :(得分:2)

如果您正在寻找正确,快速的解决方案,则应使用cold's方法,但是如果数据集很小,则可以使用

df.groupby(df.index).agg(list).apply(pd.Series)
Out[14]: 
             0       1       2
id                            
100241  Issue1  Issue2  Issue3
100242  Issue1  Issue2  Issue3