简体   繁体   中英

pandas groupby with agg not working on multiple columns

I'm trying to merge multiple columns, each into a list based on a group by in pandas. Below is the code I'm using

grouped_df = df.groupby(['d_id', 'time']).agg({'d_name': lambda x: tuple(x)},  
{'ver': lambda x: tuple(x)},
{'f_name': lambda x: tuple(x)})

This only gives me the first column (d_name) in a list with d_id and time in grouped_df. The other two columns do not show as lists. I tried using list earlier but found out that list has an issue with agg function so I resorted to tuple. Let me know if I'm doing something wrong here.

Thanks to RafaelC for the answer to this. Now I am trying to add these list columns to the original dataframe as grouped_df. When I see the columns in grouped_df they come out as

Index([u'ver', u'f_name', u'd_name'], dtype='object')

But when I do a head, I get

 ver  \
d_id  time
1    2018-06-01   (ver1, ver2, ver3.....
2    2018-06-01   (ver1, ver2, ver3.....
3    2018-06-01   (ver1, ver2, ver3.....


f_name  \
d_id   time
1  2018-06-01   (f_name1, f_name2, f_name2.....
2  2018-06-01   (f_name1, f_name2, f_name2.....
3  2018-06-01   (f_name1, f_name2, f_name2.....

d_name
d_id   time
1 2018-06-01   (d_name1, dname2, d_name3...
2 2018-06-01   (d_name1, dname2, d_name3...
3 2018-06-01   (d_name1, dname2, d_name3...

How do I get the following d_id time ver d_name f_name where ver, d_name and f_name are lists.

Hope this is clear.

使用单个参数而不是三个

{'d_name': lambda x: tuple(x), 'ver': lambda x: tuple(x), 'f_name': lambda x: tuple(x)}

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