有没有一种快速的方法可以“子扁平化”或仅扁平化numpy数组中的前几个维度?
例如,给定一个尺寸为
例如,给定一个尺寸为
(50,100,25)
的numpy数组,结果尺寸将为(5000,25)
。请参考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)
arr.flatten(dimensions=(0, 1))
。 - Denziloearr.reshape((-1,2))
。 - אלימלך שרייברarr.reshape(arr.shape[0] * arr.shape[1], arr.shape[2])
。 - Adrien Pavao对 Alexander 回答的轻微概括 - np.reshape 可以将 -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.vstack
非常适合这种情况。
import numpy as np
arr = np.ones((50,100,25))
np.vstack(arr).shape
> (5000, 25)
我更喜欢使用 stack
,vstack
或者 hstack
而不是 reshape
,因为 reshape
只是简单地扫描数据,并将其强制转换成所需的形状。如果你要计算列平均值,这可能会导致问题。
以下是一个例子来说明我的观点。假设我们有以下数组:
>>> 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]]])
>>> arr.reshape((3,8)).shape
(3, 8)
>>> np.hstack(arr).shape
(3, 8)
hstack
可以让我们获取列求和结果,这也可以从原始数组中计算得出。使用reshape就不可能实现这一点。>>> 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]])
另一种方法是使用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
your_array[50:100, 7, :]
,这将把3D对象压缩成2D,仅使用第二维的切片编号7。 - Eric Leschinskiarray[0:50,7,:]
,这将给出大小为(50,25)
的结果,舍弃了99%的数据。 - Sherman