我正在使用numpy,为了创建一个异构数组,有必要使用dtype()函数。在阅读了一些关于这个函数的python文档后,我想我知道它是如何工作的;
t = np.dtype([('name', str),('edad',int)]) <-- This tells to python that my array will have a new data type with a string named 'name' and an int named 'edad'.
R = np.array([('Rosendo',15)]) <-- And now everything I put with this other python will try to convert to str and int.这是创建异构阵列的正确方法吗?我的数组项目必须总是元组吗?我看到一些人这样写代码:
t = dtype([('name', str_, 40), ('numitems', int32), ('price',float32)])但是这是行不通的,那么"40“这个词呢('name',str_,40)。有没有其他方法可以使用dtype()创建异构数组?
发布于 2020-07-20 06:14:22
要创建结构化数组,您需要指定复合数据类型,并将数据指定为元组列表:
In [98]: dt = np.dtype([('name', 'U10'),('edad',int)])
In [99]: R = np.array([('Rosendo',15)], dtype=dt)
In [100]: R
Out[100]: array([('Rosendo', 15)], dtype=[('name', '<U10'), ('edad', '<i8')])
In [101]: R['name']
Out[101]: array(['Rosendo'], dtype='<U10')通常,按字段指定数据更容易:
In [102]: R = np.zeros((3,), dt)
In [103]: R
Out[103]:
array([('', 0), ('', 0), ('', 0)],
dtype=[('name', '<U10'), ('edad', '<i8')])
In [104]: R['name'] = ['one','two','three']
In [105]: R['edad'] = [101, 93, 3]
In [106]: R
Out[106]:
array([('one', 101), ('two', 93), ('three', 3)],
dtype=[('name', '<U10'), ('edad', '<i8')])https://stackoverflow.com/questions/62985033
复制相似问题