简体   繁体   中英

Python: pandas data frame convert string and values into column category

I would like to process with the grouped dataset below (the command lead to the below result is df.groupby(['ids','category'])['counts'].sum() )

ids|category|counts
1   A        3
2   B        5
3   A        1
    B        1
    C        1
4   C        3

What I am trying to get is below (every unique id with one row so that I can merge with another data table later):

ids|A_n|B_n|C_n
1   3    0   0
2   0    5   0
3   1    1   1
4   0    0   3

Is this possible? Any thoughts are welcome, thank you in advance!

Just unstack and fillna

group_df.unstack('category').fillna(0)

Output

         counts          
category      A    B    C
ids                      
1           3.0  0.0  0.0
2           0.0  5.0  0.0
3           1.0  1.0  1.0
4           0.0  0.0  3.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