简体   繁体   中英

Python pandas - How to correctly transpose this data?

I am using pandas to transform a Data Frame that looks like this:

        Id     Question   Answer
54      49477  Color      Red
60      49477  Base       Standard
133     49204  Color      Blue
171     49204  Base       Extended
254     48993  Color      Blue
292     48993  Base       Standard

I'm trying to figure out how to aggregate the data and append data together so that the resulting Data Frame looks like this:

       Id     Question    Answer
       49477  Color,Base  Red,Standard
       49204  Color,Base  Blue,Extended
       48993  Color,Base  Blue,Standard

Any guidance on how I can approach this?

Using groupby + agg and join

df.groupby('Id').agg(','.join)
Out[180]: 
         Question         Answer
Id                              
48993  Color,Base  Blue,Standard
49204  Color,Base  Blue,Extended
49477  Color,Base   Red,Standard

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