在列上翻转Pandas数据框并创建字典

Cod*_*key 4 python pandas

我有一个包含2列的Pandas数据帧,例如

   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
Run Code Online (Sandbox Code Playgroud)

我需要的是一本字典:

{"a": ["01", "03"],
 "b": ["04", "05", "06", "08", "09", "12"],
 "c": ["01", "02", "03", "04"]}
Run Code Online (Sandbox Code Playgroud)

我觉得这应该与groupby("名称")或枢轴一起工作,但我无法弄清楚如何.

roo*_*oot 7

执行后groupby,使用apply获取列表,然后调用to_dict:

df.groupby('name')['case'].apply(list).to_dict()
Run Code Online (Sandbox Code Playgroud)

结果输出:

{'a': ['01', '03'], 'c': ['01', '02', '03', '04'], 'b': ['04', '05', '06', '08', '09', '12']}
Run Code Online (Sandbox Code Playgroud)