【发布时间】:2019-10-08 00:29:31
【问题描述】:
这段代码(sn-p_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')
此代码 (sn-p_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 设置为现有的结构化数组?类似 sn-p_3 的东西?
我为什么要这样做?因为在sn-p_1的设置里有一个方便的访问数据的方法。
x['name']
如果我可以将“列名”添加到现有数组中,那就太好了。
【问题讨论】:
-
为什么要设置现有结构化数组的dtype? dtype 是数组的一个属性。你可以得到它,但我认为你不能改变它,特别是如果它已经有数据的话。