[英]Python - to_dict() creates unwanted nested dictionary
Edit: the duplicate suggested was not able to resolve my issue as the indexed column is different from turning a normal df into a dict. 编辑:建议的重复项无法解决我的问题,因为索引列与将普通df转换为字典不同。 Would appreciate it if the downvoter takes away the vote.
如果下降投票者放弃了投票,将不胜感激。
Very simple, I want to create a dictionary from a df, with the df indexes as keys, and a column called 'signal' as key-values. 非常简单,我想从df创建一个字典,以df索引作为键,并以“ signal”列作为键值。 I've used the to_dict() method, however this produces a nested dictionary, rather than individual.
我使用了to_dict()方法,但是这会产生一个嵌套的字典,而不是单个字典。 Code:
码:
df:
index signal
james.mccallum 0
john.driscoe 1
... ...
andrew.black 0
input:
score_dict = df.to_dict()
produces:
score_dict = {signal{james.mccallum: 0, john.driscoe: 1, ... andrew.black: 0}
desired:
score_dict = {james.mccallum: 0, john.driscoe: 1, ... andrew.black: 0}
I'm sure it's a simple fix, however have not been able to find anything related to what I want to do. 我敢肯定这是一个简单的解决方法,但是还没有找到与我想做的事情有关的任何事情。 Any help would be appreciated.
任何帮助,将不胜感激。
This is the intended behavior of to_dict
(check this very good answer with inputs/outputs of the different possible args, followed with explanations on them). 这是
to_dict
的预期行为(请使用不同可能的args的输入/输出检查此很好的答案 ,然后对其进行解释)。
In your case, just get all signal
related values 在您的情况下,只需获取所有
signal
相关值
>>> score_dict = df.to_dict()['signal']
{'james.mccallum': 0, 'john.driscoe': 1, 'andrew.black': 0}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.