193

有没有一种快速的方法来“亚展平”或展平 numpy 数组中的一些第一个维度?

例如,给定一个 numpy 维度数组(50,100,25),结果维度将是(5000,25)

4

4 回答 4

179

看看numpy.reshape

>>> 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)
于 2013-09-12T07:27:33.007 回答
104

对亚历山大的回答稍作概括 - np.reshape 可以将 -1 作为参数,意思是“数组总大小除以所有其他列出的维度的乘积”:

例如展平除最后一个维度之外的所有维度:

>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)
于 2014-10-24T18:14:30.337 回答
59

对彼得的回答稍作概括——如果您想超越三维数组,您可以在原始数组的形状上指定一个范围。

例如展平除最后两个维度之外的所有维度:

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)
于 2017-12-11T12:31:22.013 回答
3

另一种方法是使用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
于 2019-04-23T02:30:17.183 回答