设置数组的dtypes时出错

时间:2016-09-08 19:37:37

标签: python arrays numpy

我试图使用以下代码制作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

1 个答案:

答案 0 :(得分:2)

首先,我不确定f10是否已知。

请注意,结构化数组需要定义为“元组列表”。请尝试以下方法:

testArray = np.array([(19010913, "Hershey", "Bar", "Birthday", 12.34)],
dtype=[('f0','<i8'),('f1','<U64'),('f2','<U64'),('f3','<U64'),('f4','<f8')])

另请参阅thisthis了解定义np.dtype和结构化数组的不同方法。

编辑:

对于同一结构中的多行,将数组的每一行定义为列表中的单独元组。

dt = np.dtype([('f0','<i8'),('f1','<U64'),('f2','<U64'),('f3','<U‌64'),('f4','<f8')])

testArray = np.array([(19010913, "Hershey", "Bar", "Birthday", 12.34), (123, "a", "b", "c", 56.78)], dtype=dt)
相关问题