0

一般来说,我的问题是关于创建/附加到嵌套结构化数组的可能方法。特别是dtype结构已知的地方,但嵌套元素的大小没有预先定义。我用join_byandfromarray方法尝试了不同的东西,但没有成功。文档示例似乎表明连接类型方法对于某种“压缩”数据很有用,而不是真正扩展它?

定义的数据类型

from numpy.lib import recfunctions as rfn
c = [('x','f8'),('y','f8')]
d = [('text','|S20'),('val', c)]

创建 2 行 'd'

zeros = np.zeros(2, dtype=d)
print(f'{zeros=}')

如何制作多行'c'?

c = [('x','f8'),('y','f8')]
# Add a number to the construct for 'c'
d = [('text','|S20'),('val', c, 3)]
zeros = np.zeros(2, dtype=d)
print(f'{zeros=}')

如何在不预先定义“c”大小的情况下做到这一点?附加/扩展嵌套元素似乎不起作用在最低级别,“c”可用于构造一个recarray

large_c = np.arange(2*3).reshape(3,2)
struct_c = rfn.unstructured_to_structured(large_c, np.dtype(c))
print(f'{struct_c=}')

但是现在,有没有办法从现有的结构化数组构造下一个层次?我认为构造一个形状似乎可以广播的数组会起作用,但它失败了

struct_d = rfn.unstructured_to_structured(np.array(['', large_c]), np.dtype(d))
print(f'{struct_d=}')
>> The length of the last dimension of arr must be equal to the number of fields in dtype

我还尝试了重新排列结构,它们有自己的问题

struct_d = np.core.records.fromarrays(np.array(['', large_c]), dtype=d)
print(f'{struct_d=}')
>>> array-shape mismatch in array 1
4

1 回答 1

0

我认为制作这样一个数组最直接的方法是:

In [352]: c = [('x','f8'),('y','f8')]
     ...: # Add a number to the construct for 'c'
     ...: d = [('text','|S20'),('val', c, 3)]
     ...: zeros = np.zeros(2, dtype=d)
In [353]: zeros
Out[353]: 
array([(b'', [(0., 0.), (0., 0.), (0., 0.)]),
       (b'', [(0., 0.), (0., 0.), (0., 0.)])],
      dtype=[('text', 'S20'), ('val', [('x', '<f8'), ('y', '<f8')], (3,))])

In [355]: x = np.arange(12).reshape(2,3,2)

In [357]: carr = rf.unstructured_to_structured(x,np.dtype(c))
In [358]: carr
Out[358]: 
array([[( 0.,  1.), ( 2.,  3.), ( 4.,  5.)],
       [( 6.,  7.), ( 8.,  9.), (10., 11.)]],
      dtype=[('x', '<f8'), ('y', '<f8')])

使用正确的形状和 dtype,它可以分配给更大的数组:

In [359]: zeros['val']=carr
In [360]: zeros
Out[360]: 
array([(b'', [( 0.,  1.), ( 2.,  3.), ( 4.,  5.)]),
       (b'', [( 6.,  7.), ( 8.,  9.), (10., 11.)])],
      dtype=[('text', 'S20'), ('val', [('x', '<f8'), ('y', '<f8')], (3,))])

我不确定你的问题中是否有我掩盖的东西。

于 2022-01-13T00:48:00.183 回答