python: 从 dict 到 df 再回到 dict

python: From dict to df and back to dict again

假设我们有这个字典

d = {'A':True, 'B':False, 'C':True}

通过这个命令,我得到了这个想要的数据帧:

import pandas as pd
df = pd.DataFrame(d.items())

   0      1
0  A   True
1  B  False
2  C   True

但是当我想转换回字典时,我得到了这个:

d_again = df.to_dict('records')

[{0: 'A', 1: True}, {0: 'B', 1: False}, {0: 'C', 1: True}]

这和第一个dict d不一样

感谢您的帮助! :)

您可以使用数据框的 values 属性并将其传递给 dict

d_again = dict(df.values)
{'A': True, 'B': False, 'C': True}

直接翻译为

print(df.set_index(0)[1].to_dict())

产生

{'A': True, 'B': False, 'C': True}

完整代码:

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