key: pandas, DataFrame, dict, Series
df = pd.DataFrame({"a":[1,1,1,2,2,2,2,3], "b": ["q","q","q","q","q","q","q","w"], "c":[0,0,0,0,0,0,0,0], "d": [1,1,1,1,1,1,1,1]})
# output
a b c d
0 1 q 0 1
1 1 q 0 1
2 1 q 0 1
3 2 q 0 1
4 2 q 0 1
5 2 q 0 1
6 2 q 0 1
7 3 w 0 1
将a
,b
两列转成字典。
尝试1
df[["a", "b"]].to_dict(orient='dict')
# output
{'a': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 2, 7: 3},
'b': {0: 'q', 1: 'q', 2: 'q', 3: 'q', 4: 'q', 5: 'q', 6: 'q', 7: 'w'}}
分析:这样简单粗暴的转型并不是哦们想要的结果。字典内容的key
是0-n
这样的索引。所以尝试设置index
。
尝试2
df[["a", "b"]].set_index("a").to_dict(orient='dict')
# output
{'b': {1: 'q', 2: 'q', 3: 'w'}}
分析:结果好多了,但确是一个嵌套字典。
尝试3
df[["a", "b"]].set_index("a").to_dict(orient='dict')["b"]
# output
{1: 'q', 2: 'q', 3: 'w'}
这就是我们想要的结果了。