python - 如何描述两个字典的比率的笛卡尔乘法?

标签 python pandas numpy networkx

我有两本字典,如下所示:

first_dict = {"key1": 1, "key2":2, "key3":3}
sec_dict = {"key1": 2, "key2": 3, "key3":4}

我想使用 networkx 或 numpy 来创建如下矩阵:

[[1/2, 2/2, 3/2],
 [1/3, 2/3, 3/3], 
 [3/2, 3/3, 3/4]]

描述了first_dict和sec_dict中每个节点的比例。 有人可以帮我解决这个问题吗?

最佳答案

以下 NumPy 解决方案有效。在提取值之前必须对字典进行排序,除非您确定它们已经按排序顺序排列。

_, vals1 = zip(*sorted(first_dict.items()))
_, vals2 = zip(*sorted(sec_dict.items()))

如果之前已经排序过,可以忽略排序:

vals1 = list(first_dict.values())
vals2 = list(sec_dict.values())

np.array(vals1).reshape(-1,1) / np.array(vals2)

#array([[0.5       , 0.33333333, 0.25      ],
#       [1.        , 0.66666667, 0.5       ],
#       [1.5       , 1.        , 0.75      ]])

关于python - 如何描述两个字典的比率的笛卡尔乘法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58796453/

相关文章:

Python;计算向量的元素

python - 从用户定义的环境启动时,为什么 Spyder 5.0.0 应用程序启动错误?

python - 添加后列表的最后一项没有改变

python - 如果长度小于 x 则替换字符串

python - 如何获得 Pandas 数据框或系列图中使用的标准颜色?

Python数据帧: fill text in certain rows if other columns satisfied

python - 如何在这个 pandas 数据框中分组、排序和计算差异?

python - 如何将列表列表转换为数据框并将列表的第一个元素作为索引

python - 当用户购买某个类别时,查找其他类别的销售情况?

numpy - 类型错误 : ufunc 'subtract' did not contain a loop with signature matching types dtype ('<U1' ) dtype ('<U1' ) dtype ('<U1' )