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.
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']}
                        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]}
Conclusion: @root's answer is faster.
Example Data

1 million rows

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With