Pandas groupby two columns then get dict for values

前端 未结 2 1018
难免孤独
难免孤独 2020-12-31 09:39

I have a pandas dataframe:

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


        
2条回答
  •  北海茫月
    2020-12-31 10:29

    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
    

提交回复
热议问题