如何仅展平numpy数组的某些维度

时间:2013-09-12 07:12:22

标签: python numpy flatten

是否有一种快速的方法可以在numpy数组中“逐渐展平”或压平一些第一维?

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

4 个答案:

答案 0 :(得分:92)

看看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)

答案 1 :(得分:69)

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

e.g。除了最后一个维度之外的所有内容:

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

答案 2 :(得分:21)

对彼得的回答略微概括 - 如果你想要超越三维数组,你可以指定原始数组形状的范围。

e.g。除了最后的两个维度之外的所有内容:

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)

答案 3 :(得分:0)

另一种方法是使用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