Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing/Transposing Pandas Dataframe

I got the following pandas dataframe:

Id    Category
1     type 2
1     type 3
1     type 2
2     type 1
2     type 2

I need to process and transpose the above data frame to:

Id Category_type_1 Category_type_2 Category_type_3
1          0               2              1
2          1               1              0

Appreciate if anyone could shows the easiest way to code this in python.

like image 611
iLoeng Avatar asked Aug 25 '26 15:08

iLoeng


1 Answers

I'd groupby and use size

df.groupby(df.columns.tolist()).size().unstack().fillna(0)

enter image description here

like image 148
piRSquared Avatar answered Aug 27 '26 04:08

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!