简体   繁体   中英

How to split aggregated list into multiple columns in pandas

I want to create separate columns for each item in the 'name' lists for each row in this pandas dataframe. The 'name' lists have between 1-10 items, and I just want the column heads to be "1", "2", "3", etc.

out = dataframe.groupby(by=['location'], as_index=False).agg({'people':'sum', 'name':list})

Is there a way to split the aggregated list like this?

This is my original dataframe: 这是我的原始数据框

This is the dataframe I want to have: 这就是我要的

This can be done by two steps, cumcount with pivot

out1 = dataframe.groupby('location').agg({'people':'sum'})
out2 = dataframe.assign(key = dataframe.groupby('location').cumcount()).pivot('location', 'key', 'name')
out = out1.join(out2).reset_index()

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