简体   繁体   中英

Convert a Pandas DataFrame to a dictionary with values of same class together

I have a DataFrame with two columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be keys and the element of other column be values.

   item_cat_id  item_id
0            0       12
1            2       11
2            1       13
3            3       20
4            1       22
5            1       19
6            2       15
7            0       25

I want my output as dictionary:

{'0': [12,25], '1': [13,22,19], '2': [11,15], '3': [20]}

df.groupby('item_cat_id')['item_id'].apply(list).to_dict()

Sample Data:

    Animal  Number_legs
0   fox         4
1   Kangaroo    2
2   deer        4
3   spider      8
4   fox         7

Code:

df.groupby('Animal')['Number_legs'].apply(list).to_dict()

Result:

{'Kangaroo': [2], 'deer': [4], 'fox': [4, 7], 'spider': [8]}

Alternative solution:

df.groupby('item_cat_id').item_id.agg(lambda x: list(x)).to_dict()

result:

{0: [12, 25], 1: [13, 22, 19], 2: [11, 15], 3: [20]}

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