'How to change specific column to rows without changing the other columns in pandas?
I have dataframe like this:
Date ID Age Gender Fruits
1.1.19 1 50 F Apple
2.1.19 1 50 F Mango
2.1.19 1 50 F Orange
1.1.19 2 75 M Grapes
4.1.19 3 20 M Apple
4.1.19 3 20 M Grapes
I want to convert the Fruit column into further columns which gives binary info yes/no for each person. Desired output would be like this. And the missing date should be NaN.
Date ID Age Gender Apple Mango Orange Grapes
1.1.19 1 50 F 1 0 0 0
1.1.19 2 75 M 0 0 0 1
2.1.19 1 50 F 0 1 1 0
3.1.19 NaN NaN NaN NaN NaN NaN NaN
4.1.19 3 20 M 1 0 0 1
I was thinking to use groupby but i dont need any aggregation.
Solution 1:[1]
pd.get_dummies(df, columns=['Fruits'], prefix='', prefix_sep='')
Update
pd.get_dummies(df, columns=['Fruits'], prefix='', prefix_sep='').groupby('Date').max()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |