Pandas groupby 两列然后获取值的字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37690092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:20:59  来源:igfitidea点击:

Pandas groupby two columns then get dict for values

pythonpandasdataframegroup-by

提问by Bedi Egilmez

I have a pandas dataframe:

我有一个Pandas数据框:

banned_titles = 
TitleId  RelatedTitleId
0    89989           32598
1    89989         3085083
2    95281         3085083

when I apply groupby as following

当我按如下方式申请 groupby 时

In [84]: banned_titles.groupby('TitleId').groups
Out[84]: {89989: [0, 1], 95281: [2]}

This is so close but not I want.

这是如此接近,但不是我想要的。

What I want is:

我想要的是:

{89989: [32598, 3085083], 95281: [3085083]}

Is there a way to do this?

有没有办法做到这一点?

回答by MaxU

try this:

尝试这个:

In [8]: x.groupby('TitleId')['RelatedTitleId'].apply(lambda x: x.tolist()).to_dict()
Out[8]: {89989: [32598, 3085083], 95281: [3085083]}

or as series of lists:

或作为一系列列表:

In [10]: x.groupby('TitleId')['RelatedTitleId'].apply(lambda x: x.tolist())
Out[10]:
TitleId
89989    [32598, 3085083]
95281           [3085083]
Name: RelatedTitleId, dtype: object

data:

数据:

In [9]: x
Out[9]:
   TitleId  RelatedTitleId
0    89989           32598
1    89989         3085083
2    95281         3085083

回答by Merlin

Try list one line (no lambda):

尝试列出一行(无 lambda):

dict(df.groupby('TitleId')['RelatedTitleId'].apply(list))
 # {89989: [32598, 3085083], 95281: [3085083]}