【发布时间】:2019-07-18 08:25:21
【问题描述】:
我正在将 Python 字典转换为 NumPy 数组。
import numpy as np
myDict = {
1: "AAA",
2: "BBB",
3: "CCC",
4: "AAA",
5: "BBB"
}
myNumPyArray = np.asarray(myDict, dtype=dict, order="C")
print(myNumPyArray)
输出
{1: 'AAA', 2: 'BBB', 3: 'CCC', 4: 'AAA', 5: 'BBB'}
为什么会在输出中显示字典?
【问题讨论】:
-
你可以改用
myNumPyArray = np.array(list(myDict.items()))。 -
尝试打印
repr(myNumPyArray)。 -
问题是,它是一个字典数组。 Numpy 无法知道您希望如何推断 dict,请查看 docs。在调用 numpy 数组之前,在字典上使用
.items.()或.values() -
你期望什么输出? The manual says 第一个参数应该传递“列表、元组列表、元组、元组元组、列表元组和 ndarrays”。
标签: python numpy dictionary