Ahsan
Ahsan

Reputation: 561

Pandas Dataframe Transpose

I have tried to find something that could help me but I couldn't. I'd appreciate if someone could link me to it, if my question is already answered.

I have a pandas dataframe that has row-wise features. For example:

   Patient_ID  Feature_Id  Feature_Value
0           3          10           0.30
1           3          50           0.20
2           3          60           1.00
3           4          10           0.25

I need to convert them into column-wise features(essentially columns in Pandas) -- something like below:

Patient_Id    10   50   60
         3  0.30  0.2  1.0
         4  0.25  Nan  Nan

Upvotes: 1

Views: 907

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76381

You could try pd.pivot_table

In [16]: pd.pivot_table(df, index='Patient_ID', values='Feature_Value', columns='Feature_ID')
Out[16]: 
Feature_ID    10   50   60
Patient_ID                
3           0.30  0.2  1.0
4           0.25  NaN  NaN

Note that if you need to specify what to do if more than a single entry exists (which you don't have in your example), you can use the aggfunc parameter (the default is to calculate the mean).

Upvotes: 1

Related Questions