是否有一种快速的方法来“次扁平化”或只扁平化numpy数组中的一些第一个维度?

例如,给定一个尺寸为(50,100,25)的numpy数组,结果尺寸为(5000,25)


看看numpy。重塑。

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

稍微概括一下亚历山大的答案——np。重塑可以取-1作为参数,意思是“数组总大小除以所有列出的其他维度的乘积”:

例如,将除最后一个维度外的所有维度平化:

>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)

稍微概括一下Peter的回答——如果你想超越三维数组,你可以在原始数组的形状上指定一个范围。

例如,将除最后两个维度外的所有维度平化:

arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)

编辑:稍微概括一下我之前的回答——当然,你也可以在重塑的开始指定一个范围:

arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)

另一种方法是使用numpy.resize(),如:

In [37]: shp = (50,100,25)
In [38]: arr = np.random.random_sample(shp)
In [45]: resized_arr = np.resize(arr, (np.prod(shp[:2]), shp[-1]))
In [46]: resized_arr.shape
Out[46]: (5000, 25)

# sanity check with other solutions
In [47]: resized = np.reshape(arr, (-1, shp[-1]))
In [48]: np.allclose(resized_arr, resized)
Out[48]: True

numpy。Vstack非常适合这种情况

import numpy as np
arr = np.ones((50,100,25))
np.vstack(arr).shape
> (5000, 25)

我更喜欢使用stack, vstack或hstack而不是重塑,因为重塑只是扫描数据,似乎是将其强行转换成所需的形状。这可能是有问题的,如果你要取列平均。

这里有一个例子来说明我的意思。假设我们有以下数组

>>> arr.shape
(2, 3, 4)
>>> arr 
array([[[1, 2, 3, 4],
        [1, 2, 3, 4],
        [1, 2, 3, 4]],

       [[7, 7, 7, 7],
        [7, 7, 7, 7],
        [7, 7, 7, 7]]])

我们应用这两种方法来获得一个shape(3,8)数组

>>> arr.reshape((3,8)).shape
(3, 8)
>>> np.hstack(arr).shape 
(3, 8)

然而,如果我们看看它们在每种情况下是如何被重塑的,hstack将允许我们从原始数组中计算出的列和。对于重塑来说,这是不可能的。

>>> arr.reshape((3,8))
array([[1, 2, 3, 4, 1, 2, 3, 4],
       [1, 2, 3, 4, 7, 7, 7, 7],
       [7, 7, 7, 7, 7, 7, 7, 7]])
>>> np.hstack(arr)
array([[1, 2, 3, 4, 7, 7, 7, 7],
       [1, 2, 3, 4, 7, 7, 7, 7],
       [1, 2, 3, 4, 7, 7, 7, 7]])