Reputation: 7644
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?
Upvotes: 2
Views: 3167
Reputation: 294218
Use a dictionary comprehension around the groupby
iterator
{n: v.tolist() for n, v in df.groupby('key').id}
Upvotes: 1
Reputation: 862511
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'}
Upvotes: 3