Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 270
Worst SQL Noob Avatar asked Dec 11 '18 02:12

Worst SQL Noob


2 Answers

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
like image 83
cs95 Avatar answered Sep 23 '22 15:09

cs95


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
like image 37
BENY Avatar answered Sep 26 '22 15:09

BENY