Pandas groupby两列然后获取值的dict

Bed*_*mez 11 python group-by dataframe pandas

我有一个pandas数据帧:

banned_titles = 
TitleId  RelatedTitleId
0    89989           32598
1    89989         3085083
2    95281         3085083
Run Code Online (Sandbox Code Playgroud)

当我将groupby应用于以下时

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

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

我想要的是:

{89989: [32598, 3085083], 95281: [3085083]}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Max*_*axU 27

试试这个:

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

或作为一系列清单:

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

数据:

In [9]: x
Out[9]:
   TitleId  RelatedTitleId
0    89989           32598
1    89989         3085083
2    95281         3085083
Run Code Online (Sandbox Code Playgroud)