【问题标题】:Record data type for heterogeneous Numpy arrays异构 Numpy 数组的记录数据类型
【发布时间】: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


【解决方案1】:

要创建结构化数组,您需要指定复合 dtype,并将数据指定为元组列表:

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')])

【讨论】:

    猜你喜欢
    • 2011-11-24
    • 2015-03-15
    • 2021-08-13
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    相关资源
    最近更新 更多