简体   繁体   中英

Pandas dataframe to dict on multiple columns and values to list

I have a dataframe

id    key
a1     1
a2     1
a3     1
a4     2
a5     2
a6     3

I want to create a dictionary with key as machine no, and id column as list

like:

{1: ['a1', 'a2', 'a3'], 2: ['a4', 'a5'], 3: ['a6']}

Can i use groupby first and then do .to_dict?

I believe you need lists ad values of dict - use groupby + apply + to_dict :

d = df.groupby('key')['id'].apply(list).to_dict()
print (d)
{1: ['a1', 'a2', 'a3'], 2: ['a4', 'a5'], 3: ['a6']}

Or if need list with scalars add if/else to apply :

d = df.groupby('key')['id'].apply(lambda x: list(x) if len(x) > 1 else x.iat[0]).to_dict()
print (d)
{1: ['a1', 'a2', 'a3'], 2: ['a4', 'a5'], 3: 'a6'}

groupby迭代器周围使用字典理解

{n: v.tolist() for n, v in df.groupby('key').id}

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