numpy dtype 错误 - (结构化数组创建)

numpy dtype error - (structured array creation)

我无法理解为什么以下内容不起作用:

np.dtype(dict(names="10", formats=np.float64))

我一直在努力解决这个问题,因为我想让 numpy 中的 recfunctions 函数正常工作,但是由于 numpy.dtype 的问题,我一直没有成功的。这是我目前收到的错误:

dtype = np.dtype(dict(names=names, formats=formats))
ValueError: all items in the dictionary must have the same length.

我想要一个数据结构,它包含一种记录数组,在每个分配的字段中具有多列数据 - 类似于字典,其中每个值都是一个二维数组或多列数据。通常,数据最终可能是 ~6 列,每个键或记录约 2000 行,约 200 条记录。

这是我在一个完整的脚本中尝试过的:(尽管仍然给出同样的错误)

import numpy as np
from numpy.lib import recfunctions


# Just function to make random data
def make_data(i, j):
    # some arbitrary function to show that the number of columns may change, but rows stay the same length
    if i%3==0:
        data = np.array([[i for i in range(0,1150)]*t for t in range(0,3)])
    else:
        data = np.array([[i for i in range(0,1150)]*t for t in range(0,6)])
    return data

def data_struct(low_ij, high_ij):

    """
    Data Structure to contain several columns of data for different combined values between "low ij" and "high ij"

    Key: "(i, j)"
    Value: numpy ndarray (multidimensional)
    """

    for i in range(0,low_ij+1):
        for j in range(0,high_ij+1):
            # Get rid of some of the combinations
            # (unimportant)
            if(i<low_ij and j<low_ij):
                break
            elif(i<j):
                break

            # Combinations of interest to create structure
            else:
                names = str(i)+str(j)
                formats = np.float64
                data = np.array(make_data(i, j))
                try:
                    data_struct = recfunctions.append_fields(base=data_struct, names=names, data=data, dtypes=formats)
                # First loop will assign data_struct using this exception,
                # then proceed to use the try statement to add on the rest of the data
                except UnboundLocalError:
                    dtype = np.dtype(dict(names=names, formats=formats))
                    data_struct = np.array(data, dtype=dtype)

    return data_struct

您必须传递值列表和格式列表,而不是单个值和单个格式。如果调试问题,您会发现

type(names)   # result is <type 'str'>
type(formats) # result is <type 'type'>

然后正好dict初始化为

{'formats': numpy.float64, 'names': '30'}

formatsnames 中的每一个都应该是一个列表。

编辑:此外,请注意 formats 应该是一个字符串列表,如 ['float64','u8'] 等。

看起来您正在尝试构建类似于以下内容的结构化数组:

In [152]: names=['1','2','3','4']
In [153]: formats=[(float,2),(float,3),(float,2),(float,3)]
In [154]: dt=np.dtype({'names':names, 'formats':formats})
In [156]: ds=np.zeros(5, dtype=dt)

In [157]: ds
Out[157]: 
array([([0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0], [0.0, 0.0, 0.0]),
       ([0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0], [0.0, 0.0, 0.0]),
       ([0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0], [0.0, 0.0, 0.0]),
       ([0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0], [0.0, 0.0, 0.0]),
       ([0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0], [0.0, 0.0, 0.0])], 
      dtype=[('1', '<f8', (2,)), ('2', '<f8', (3,)), ('3', '<f8', (2,)), 
           ('4', '<f8', (3,))])
In [159]: ds['1']=np.arange(10).reshape(5,2)
In [160]: ds['2']=np.arange(15).reshape(5,3)

换句话说,多个字段,每个字段具有不同数量的'columns'(形状)。

这里我创建初始化整个数组,然后单独填充字段。这似乎是创建复杂结构化数组的最直接方法。

您正在尝试逐步构建这样一个数组,从一个字段开始,然后使用 recfunctions.append_fields

添加新的数组
In [162]: i=1; 
   ds2 = np.array(np.arange(5),dtype=np.dtype({'names':[str(i)],'formats':[float]}))
In [164]: i+=1;
   ds2=recfunctions.append_fields(base=ds2,names=str(i),dtypes=float,
      data=np.arange(5), usemask=False,asrecarray=False)
In [165]: i+=1;
   ds2=recfunctions.append_fields(base=ds2,names=str(i),dtypes=float,
      data=np.arange(5), usemask=False,asrecarray=False)

In [166]: ds2
Out[166]: 
array(data = [(0.0, 0.0, 0.0) (1.0, 1.0, 1.0) (2.0, 2.0, 2.0) 
    (3.0, 3.0, 3.0) (4.0, 4.0, 4.0)], 
    dtype = [('1', '<f8'), ('2', '<f8'), ('3', '<f8')])

当附加字段都为 1 'column' 时,此方法有效。通过掩码,他们甚至可以有不同数量的 'rows'。但是当我尝试改变内部形状时,它在附加字段时遇到了问题。 marge_arrays不再成功。

即使我们可以使用增量 recfunctions 方法,它也可能比初始化和填充方法慢。即使您一开始不知道每个字段的形状,您也可以将它们全部收集在字典中,然后 assemble 从中得到数组。这种结构化数组并不比字典更紧凑或更高效。它只是使某些类型的数据访问(跨字段)更加方便。