Worst SQL Noob
Worst SQL Noob

Reputation: 189

Reshape vertical series to horizontal in Python

I have a simple series data looks like:

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

My goal is to reshape it to the horizontal format, one row for each id with its correlated issues and saved in excel, looks like

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

I am new to Python and not sure how can I achieve it using Python? Thanks.

Upvotes: 5

Views: 396

Answers (2)

BENY
BENY

Reputation: 323316

If you looking for the correct and fast solution you should using cold's method , but if just a small data set you can using

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

Upvotes: 2

cs95
cs95

Reputation: 402814

You can append a level to the index and 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

Upvotes: 5

Related Questions