我有些困惑,不明白为什么下面的代码无法正常运行:
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.
我希望获得一种数据结构,该结构将包含一个记录数组类型,并在每个分配字段内包含多列数据 - 类似于字典,其中每个值都是2D数组或多列数据。通常情况下,每个键或记录的数据可能最终为大约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