Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas transpose rows to columns based on first column

Tags:

python

pandas

I have the below dataframe.

Column_1   Column_2
Name       Xxxx
Age        28
Gender     M
Name       yyyy
Age        26
Gender     F

My expected output is

Name   Age   Gender
Xxxx   28    M
yyyy   26    F

I tried df.T(), but it's writing each name, age and gender to separate columns.

How to achieve the above output in python/pandas.

like image 503
Padfoot123 Avatar asked Mar 01 '23 11:03

Padfoot123


1 Answers

Or try groupby with agg and pd.Series.explode:

>>> df.groupby('Column_1').agg(list).T.apply(pd.Series.explode).reset_index(drop=True).rename_axis(columns=None)
  Age Gender  Name
0  28      M  Xxxx
1  26      F  yyyy
>>> 
like image 66
U12-Forward Avatar answered Mar 03 '23 23:03

U12-Forward