简体   繁体   中英

Transform unique values of a column into multiple columns containing their corresponding values in another column PYTHON

I am looking for a solution to the problem posted in:

Transform unique values of a column into multiple columns containing their corresponding values in another column

however in PYTHON.

Thanks!

You need df.pivot_table() :

df.pivot_table(index='ID',columns='Fruit',values='n',fill_value=0)

Fruit  Apple  Banana  Orange  Pear  Plum
ID                                      
1000       0       1       3     1     0
1001       0       1       0     0     2
1002       0       1       0     0     0
1003       0       1       2     1     1
1004       2       2       1     1     0
data = {'id' : 
[1000,1000,1000,1001,10001,1002,1003,1003,1003,1003,1004,1004,1004,1004],
'Fruit' :['Banana', 'Orange', 'Pear', 'Banana', 'Plum', 'Banana', 'Banana', 'Orange', 
'Pear', 'Plum', 'Apple', 'Banana', 'Orange', 'Pear'],
'num' : [1,3,1,1,2,1,1,2,1,1,2,2,1,1]}

df = pd.DataFrame(data)

import numpy as np
df.pivot(index='id', columns='Fruit', values='num').replace(np.nan, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM