如何仅展平numpy数组的某些尺寸


127

是否有一种快速的方法来“子展平”或仅展平numpy数组中的某些第一维?

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



您需要有关numpy ndarray数组切片的复习课程。也称为多维数组索引,请参阅:docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html 使用方括号对ndarray进行数组切片,并使用逗号定界符分隔每个数组的数量您想要的尺寸。它看起来像(不完全一样):your_array[50:100, 7, :]将3d对象展平为2d,仅对第二维使用切片编号7。
埃里克·莱斯钦斯基

Answers:


129

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

81

亚历山大答案的一个概括-np.reshape可以采用-1作为参数,表示“总数组大小除以所有其他列出的维数的乘积”:

例如,将除最后一个尺寸以外的所有尺寸展平:

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

33

彼得的答案略有概括-如果您想超越三维阵列,则可以在原始阵列的形状上指定一个范围。

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

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)

2
已经有两年多了……我们需要进一步的概括!;)
Lith

1

一种替代方法是按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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.