数据帧,以便一列为键,另一列为值 [英] dataframe to dict such that one column is the key and the other is the value
本文介绍了数据帧,以便一列为键,另一列为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有数据框
ID A B C
0 p 1 3 2
1 q 4 3 2
2 r 4 0 9
我想创建一个字典,其中ID是键,B是值,因此它将是:
And I want to create a dict where ID is the keys and B is the values so it will be:
d["q"] = 3 , d["r"] = 0
这样做的最好方法是什么?
What is the best way to do so?
它与假定的重复项有所不同,因为我希望每个键一个值而不是一个列表
It is different than the supposed duplicate becasue I want single value per key and not a list
推荐答案
类似以下内容:
In [27]: df
Out[27]:
ID A B C
0 p 1 3 2
1 q 4 3 2
2 r 4 0 9
In [30]: df.set_index('ID',inplace=True)
In [31]: df
Out[31]:
A B C
ID
p 1 3 2
q 4 3 2
r 4 0 9
In [33]: df.to_dict()['B']
Out[33]: {'p': 3, 'q': 3, 'r': 0}
这篇关于数据帧,以便一列为键,另一列为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文