包含可变形状的多维numpy数组的numpy数组

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

我有一个numpy数组的列表,其形状为以下之一:(10,4,4,20), (10,4,6,20)。我想将列表转换为numpy数组。因为它们的形状不同,所以我不能只堆叠它们。因此,我想到了像here一样考虑将每个数组作为一个对象来创建numpy数组。我尝试了以下方法:

b = numpy.array(a)
b = numpy.array(a, dtype=object)

其中a是numpy数组的列表。两者都给我以下错误:

ValueError: could not broadcast input array from shape (10,4,4,20) into shape (10,4)

如何将列表转换为numpy数组?

示例

import numpy
a = [numpy.random.random((10,4,4,20)),
     numpy.random.random((10,4,6,20)),
     numpy.random.random((10,4,6,20)),
     numpy.random.random((10,4,4,20)),
     numpy.random.random((10,4,6,20)),
     numpy.random.random((10,4,6,20)),
     numpy.random.random((10,4,4,20)),
     numpy.random.random((10,4,4,20)),
     numpy.random.random((10,4,6,20))
    ]
b = numpy.array(a)

用例:我知道对象的numpy数组效率不高,但是我没有对它们执行任何操作。通常,我有一个相同形状的numpy数组的列表,因此我可以轻松地堆叠它们。此数组传递给另一个函数,该函数仅选择某些元素。如果我的数据是numpy数组,则可以执行b[[1,3,8]]。但是我不能对list做同样的事情。如果我尝试与列表相同,则会出现以下错误

c = a[[1,3,8]]
TypeError: list indices must be integers or slices, not list
python arrays numpy typeerror valueerror
1个回答
1
投票
如果列表数组在第一维上不同,

np.array(alist)将创建一个对象dtype数组。但是在您的情况下,它们在第三种情况下会有所不同,从而产生此错误。实际上,它不能明确确定包含维度的终止位置以及对象的起始位置。

In [270]: alist = [np.ones((10,4,4,20),int), np.zeros((10,4,6,20),int)]                                
In [271]: arr = np.array(alist)                                                                        
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-271-3fd8e9bd05a9> in <module>
----> 1 arr = np.array(alist)

ValueError: could not broadcast input array from shape (10,4,4,20) into shape (10,4)

相反,我们需要制作一个大小合适的对象数组,并将列表复制到其中。有时,此副本仍会产生广播错误,但在这里似乎没问题:

In [272]: arr = np.empty(2, object)                                                                    
In [273]: arr                                                                                          
Out[273]: array([None, None], dtype=object)
In [274]: arr[:] = alist                                                                               
In [275]: arr                                                                                          
Out[275]: 
array([array([[[[1, 1, 1, ..., 1, 1, 1],
         [1, 1, 1, ..., 1, 1, 1],
         [1, 1, 1, ..., 1, 1, 1],
...
         [0, 0, 0, ..., 0, 0, 0],
         [0, 0, 0, ..., 0, 0, 0]]]])], dtype=object)
In [276]: arr[0].shape                                                                                 
Out[276]: (10, 4, 4, 20)
In [277]: arr[1].shape                                                                                 
Out[277]: (10, 4, 6, 20)
© www.soinside.com 2019 - 2024. All rights reserved.