【问题标题】:Is it possible to set dtype to an existing structured array, or add "column name" to an existing array?是否可以将 dtype 设置为现有的结构化数组,或将“列名”添加到现有数组?
【发布时间】: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 是数组的一个属性。你可以得到它,但我认为你不能改变它,特别是如果它已经有数据的话。

标签: python numpy


【解决方案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')])

【讨论】:

    【解决方案2】:

    给定以下输入:

    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的答案

    【讨论】:

      猜你喜欢
      • 2014-10-15
      • 1970-01-01
      • 2012-08-30
      • 2017-06-13
      • 2016-05-03
      • 2014-10-17
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      相关资源
      最近更新 更多