我试图用下面的代码制作一个 1x5 的 numpy 数组
testArray = np.array([19010913, "Hershey", "Bar", "Birthday", 12.34])
但遇到了不想要的结果
testArray.dtype
dtype("<U8")
我希望每一列都是特定的数据类型,所以我尝试输入这个
testArray = np.array([19010913, "Hershey", "Bar", "Birthday", 12.34],
dtype=[('f0','<i8'),('f1','<U64'),('f2','<U64'),('f3','<U64'),('f4','<f10')] )
但得到了错误
/usr/local/lib/python3.4/dist-packages/ipykernel/__main__.py:1:
DeprecationWarning: Specified size is invalid for this data type.
Size will be ignored in NumPy 1.7 but may throw an exception in
future versions. if __name__ == '__main__':
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-d2c44d88c8a5> in <module>()
----> 1 testArray = np.array([19840913, "Hershey", "Bar",
"Birthday", 64.25], dtype=[('f0','<i8'),('f1','<U64'),('f2','<U64'), ('f3','<U64'),('f4','<f10')] )
TypeError: 'int' does not support the buffer interface
请您参考如下方法:
首先,我不确定 f10 是否已知。
请注意,结构化数组需要定义为“元组列表”。尝试以下操作:
testArray = np.array([(19010913, "Hershey", "Bar", "Birthday", 12.34)],
dtype=[('f0','<i8'),('f1','<U64'),('f2','<U64'),('f3','<U64'),('f4','<f8')])
另见 this和 this用于定义 np.dtype 和结构化数组的不同方式。
编辑:
对于同一结构中的多行,将数组的每一行定义为列表中的单独元组。
dt = np.dtype([('f0','<i8'),('f1','<U64'),('f2','<U64'),('f3','<U64'),('f4','<f8')])
testArray = np.array([(19010913, "Hershey", "Bar", "Birthday", 12.34), (123, "a", "b", "c", 56.78)], dtype=dt)
