简体   繁体   English

与agg的pandas groupby无法在多列上使用

[英]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. 这只给我列表中的第一列(d_name),d_id和time在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. 我尝试过使用list,但是发现list的agg函数有问题,所以我求助于元组。 Let me know if I'm doing something wrong here. 让我知道我在这里做错了什么。

Thanks to RafaelC for the answer to this. 感谢RafaelC的答案。 Now I am trying to add these list columns to the original dataframe as grouped_df. 现在,我尝试将这些列表列作为grouped_df添加到原始数据框。 When I see the columns in grouped_df they come out as 当我看到grouped_df中的列时,它们显示为

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. 如何获得以下d_id时间ver d_name f_name,其中ver,d_name和f_name是列表。

Hope this is clear. 希望这很清楚。

使用单个参数而不是三个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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