此代码(snippet_1)用于构造一个structured array
>>> dt = np.dtype([('name', np.str_, 16), ('age', np.int)])
>>> x = np.array([('Sarah', 16), ('John', 17)], dtype=dt)
>>> x
array([('Sarah', 16), ('John', 17)],
dtype=[('name', '<U16'), ('age', '<i8')])
此代码是将dtype设置为给定的简单数组
arr = np.array([10, 20, 30, 40, 50])
arr = arr.astype('float64')
此代码(snippet_3)试图将dtype设置为结构化数组,
x = np.array([('Sarah', 16), ('John', 17)])
x = x.astype(dt)
当然,以这种方式设置dtype会导致ValueError
ValueError Traceback (most recent call last)
<ipython-input-18-201b69204e82> in <module>()
1 x = np.array([('Sarah', 16), ('John', 17)])
----> 2 x = x.astype(dt)
ValueError: invalid literal for int() with base 10: 'Sarah'
是否可以将dtype设置为现有的结构化数组?像snippet_3这样的东西?
我为什么要这样做?因为在snippet_1的设置中可以方便地访问数据。
x['name']
如果我可以在现有数组中添加“列名”,那就太酷了。
答案 0 :(得分:1)
您可以使用numpy.lib.recfunctions.unstructured_to_structured
x = np.array([('Sarah', 16), ('John', 17)])
x
# array([['Sarah', '16'],
# ['John', '17']], dtype='<U5')
dt = np.dtype([('name', np.str_, 16), ('age', np.int)])
import numpy.lib.recfunctions as nlr
xs = nlr.unstructured_to_structured(x, dtype=dt)
xs
# array([('Sarah', 16), ('John', 17)],
# dtype=[('name', '<U16'), ('age', '<i8')])
答案 1 :(得分:0)
提供以下输入:
dt = np.dtype([('name', np.str_, 16), ('age', np.int)])
x = np.array([('Sarah', 16), ('John', 17)], dtype=dt)
# array([('Sarah', 16), ('John', 17)],
# dtype=[('name', '<U16'), ('age', '<i8')])
让我们添加一列到结构化数组,如下所示:
new_dt = np.dtype(x.dtype.descr + [('weight', float)])
xx = np.zeros(x.shape, dtype=new_dt)
xx['name'] = x['name']
xx['age'] = x['age']
xx['weight'] = [86.7, 78.9]
并给出:
# array([('Sarah', 16, 86.7), ('John', 17, 78.9)],
# dtype=[('name', '<U16'), ('age', '<i8'), ('weight', '<f8')])
要更改结构化数组中的数据类型,请查看@PaulPanzer
的答案