【发布时间】:2020-07-19 19:59:21
【问题描述】:
我正在使用 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)])
但这行不通,那么 ('name', str_, 40) 上的“40”怎么样。 还有其他方法可以使用 dtype() 创建异构数组吗?
【问题讨论】:
-
见Numpy: Structured arrays。每个维度(想想列)都有一个名称和一个类型。
x = np.array([('Rex', 9, 81.0), ('Fido', 3, 27.0)], dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')])。 SO: structured array questions. -
这是结构化数组,不是异构数组。
-
数组项不是元组,但
np.array构造函数将要求您传递元组,如果您想创建结构化数组。 -
谢谢,什么是异构数组?
-
您不能在复合数据类型中使用“通用”
str。必须指定长度,例如'U10`。
标签: python arrays numpy user-defined-types structured-array