gpt4 book ai didi

python - 如何在python中有效地将子字典转换为矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:46 24 4
gpt4 key购买 nike

我有这样一本字典:

{'test2':{'hi':4,'bye':3}, 'religion.christian_20674': {'path': 1, 'religious': 1, 'hi':1}}

这个字典的值本身就是一个字典。

我的输出应该是这样的:

enter image description here

我怎样才能有效地做到这一点?

我已阅读 this帖子,矩阵的形状和我的不一样。

this一个最接近我的情况,但它在字典中有一个集合而不是另一个字典。

我的问题的不同之处在于我还想将内部字典的值转换为矩阵的值。

我是这样想的:

doc_final =[[]]
for item in dic1:
for item2, value in dic1[item]:
doc_final[item][item2] = value

但这不是正确的方法。

感谢您的帮助:)

最佳答案

使用 pandas 库,您可以轻松地将字典转换为矩阵。

代码:

import pandas as pd

d = {'test2':{'hi':4,'bye':3}, 'religion.christian_20674': {'path': 1, 'religious': 1, 'hi':1}}
df = pd.DataFrame(d).T.fillna(0)

print(df)

输出:

                          bye   hi  path  religious
test2 3.0 4.0 0.0 0.0
religion.christian_20674 0.0 1.0 1.0 1.0

关于python - 如何在python中有效地将子字典转换为矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com