[英]python: From dict to df and back to dict again
Suppose we have this dict假设我们有这个字典
d = {'A':True, 'B':False, 'C':True}
With this command, I get this desired Dataframe:使用此命令,我得到了所需的 Dataframe:
import pandas as pd
df = pd.DataFrame(d.items())
0 1
0 A True
1 B False
2 C True
But when I want to transform back to a dict, I get this:但是当我想转换回字典时,我得到了这个:
d_again = df.to_dict('records')
[{0: 'A', 1: True}, {0: 'B', 1: False}, {0: 'C', 1: True}]
Which its not the same as the first dict d.这与第一个 dict d 不同。
Thank you for your help: :)谢谢您的帮助: :)
You can use values
attribute of the dataframe and pass it to dict
您可以使用 dataframe 的
values
属性并将其传递给dict
d_again = dict(df.values)
{'A': True, 'B': False, 'C': True}
The direct translation would be直接翻译是
print(df.set_index(0)[1].to_dict())
Which yields哪个产量
{'A': True, 'B': False, 'C': True}
Full code:完整代码:
import pandas as pd
dct_in = {'A':True, 'B':False, 'C':True}
df = pd.DataFrame(dct_in.items())
dct_out = df.set_index(0)[1].to_dict()
assert dct_in == dct_out
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.