Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flip Pandas dataframe on column and create dictionary

Tags:

python

pandas

I have a Pandas dataframe with 2 columns, e.g.

   name case
0  a    01
1  a    03
2  b    04
3  b    05
4  b    06
5  b    08
6  b    09
7  b    12
8  c    01
9  c    02
10 c    03
11 c    04

What I need is a dictionary:

{"a": ["01", "03"],
 "b": ["04", "05", "06", "08", "09", "12"],
 "c": ["01", "02", "03", "04"]}

I have the feeling this should work with groupby("name") or pivot, but I can't figure out how.

like image 733
CodeMonkey Avatar asked Feb 06 '23 14:02

CodeMonkey


2 Answers

After performing the groupby, use apply to get a list, and then call to_dict:

df.groupby('name')['case'].apply(list).to_dict()

The resulting output:

{'a': ['01', '03'], 'c': ['01', '02', '03', '04'], 'b': ['04', '05', '06', '08', '09', '12']}
like image 184
root Avatar answered Feb 11 '23 18:02

root


For some perspective:

s = df.set_index('name').case
{k: s.loc[k].tolist() for k in s.index.unique()}

{'a': [1, 3], 'b': [4, 5, 6, 8, 9, 12], 'c': [1, 2, 3, 4]}

Timing

Conclusion: @root's answer is faster.

Example Data

enter image description here

1 million rows

enter image description here

like image 33
piRSquared Avatar answered Feb 11 '23 18:02

piRSquared