Jack Friend
Jack Friend

Reputation: 31

Groupby Row element and Tranpose a Panda Dataframe

In Python, I have the following Pandas dataframe:

     Factor     Value
0    a          1.2
1    b          3.4
2    b          4.5
3    b          5.6
4    c          1.3
5    d          4.6

I would like to organize this where:

The factor values are not in an organized.

Target:

     A     B    C     D
0    1.2   3.4  1.3   4.6     
1          4.5
2          5.6  
3            
4       
5            

Upvotes: 2

Views: 38

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Use, set_index and unstack with groupby:

df.set_index(['Factor', df.groupby('Factor').cumcount()])['Value'].unstack(0)

Output:

Factor    a    b    c    d
0       1.2  3.4  1.3  4.6
1       NaN  4.5  NaN  NaN
2       NaN  5.6  NaN  NaN

Upvotes: 2

Related Questions