将列表的ndarray转换为ndarray

问题描述 投票:0回答:2

nda.shape为(2,2),将其转换为(2,2,2)

dtypes = [('a', np.float64), ('b', object)]
nda = np.zeros((2,2), dtype = dtypes)

nda['b'][0,0] = [1,2]
nda['b'][1,0] = [2,3]
nda['b'][0,1] = [3,4]
nda['b'][1,1] = [9,5]

解决方案应提供:nda['b'][0,0,1]==2nda['b'][1,1,0]==9

python numpy numpy-ndarray
2个回答
0
投票

尝试以下操作

nda = np.resize(nda, (2,2,2))
nda.shape

结果

(2,2,2)

0
投票

您创建了一个奇怪的结构;您不能简单地重塑它:

In [1]: dtypes = [('a', np.float64), ('b', object)] 
   ...: nda = np.zeros((2,2), dtype = dtypes) 
   ...:  
   ...: nda['b'][0,0] = [1,2] 
   ...: nda['b'][1,0] = [2,3] 
   ...: nda['b'][0,1] = [3,4] 
   ...: nda['b'][1,1] = [9,5]   

它有2个字段,一个带有数字,另一个带有列表:

In [2]: nda                                                                     
Out[2]: 
array([[(0., list([1, 2])), (0., list([3, 4]))],
       [(0., list([2, 3])), (0., list([9, 5]))]],
      dtype=[('a', '<f8'), ('b', 'O')])

列表字段:

In [3]: nda['b']                                                                
Out[3]: 
array([[list([1, 2]), list([3, 4])],
       [list([2, 3]), list([9, 5])]], dtype=object)
In [4]: _.shape                                                                 
Out[4]: (2, 2)

如果转换为1d,我们可以stack(或与concatenate结合使用:]

In [5]: nda['b'].ravel()                                                        
Out[5]: 
array([list([1, 2]), list([3, 4]), list([2, 3]), list([9, 5])],
      dtype=object)
In [6]: np.stack(nda['b'].ravel())                                              
Out[6]: 
array([[1, 2],
       [3, 4],
       [2, 3],
       [9, 5]])
In [7]: np.stack(nda['b'].ravel()).reshape(2,2,2)                               
Out[7]: 
array([[[1, 2],
        [3, 4]],

       [[2, 3],
        [9, 5]]])

[通常,如果您具有列表或数组的对象dtype数组,则可以将其合并为一个具有concatenate排序版本的(数字)数组,但必须为1d,即数组/列表的“可迭代”。] >

而且,是的,将字段解压缩到嵌套列表中会产生一些可以转换回(2,2,2)数组的东西:

In [14]: _2['b'].tolist()                                                       
Out[14]: [[[1, 2], [3, 4]], [[2, 3], [9, 5]]]

((您不能简单地将这些数组(或列表)放回nda数组。dtype错误。)

具有不同的dtype(`b字段是2个整数,不是更通用的对象):

In [10]: dtypes = [('a', np.float64), ('b', int, (2,))] 
    ...: nda = np.zeros((2,2), dtype = dtypes) 
    ...:  
    ...: nda['b'][0,0] = [1,2] 
    ...: nda['b'][1,0] = [2,3] 
    ...: nda['b'][0,1] = [3,4] 
    ...: nda['b'][1,1] = [9,5]                                                  
In [11]: nda                                                                    
Out[11]: 
array([[(0., [1, 2]), (0., [3, 4])],
       [(0., [2, 3]), (0., [9, 5])]],
      dtype=[('a', '<f8'), ('b', '<i8', (2,))])
In [12]: nda['b']                                                               
Out[12]: 
array([[[1, 2],
        [3, 4]],

       [[2, 3],
        [9, 5]]])
    
© www.soinside.com 2019 - 2024. All rights reserved.