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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18757742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:43:24  来源:igfitidea点击:

How to flatten only some dimensions of a numpy array

pythonnumpyflatten

提问by Curious

Is there a quick way to "sub-flatten" or flatten only some of the first dimensions in a numpy array?

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

For example, given a numpy array of dimensions (50,100,25), the resultant dimensions would be (5000,25)

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

采纳答案by Alexander

Take a look at numpy.reshape.

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

回答by Peter

A slight generalization to Alexander's answer - np.reshape can take -1 as an argument, meaning "total array size divided by product of all other listed dimensions":

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

e.g. to flatten all but the last dimension:

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

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

回答by KeithWM

A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.

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

e.g. to flatten all but the last twodimensions:

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

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

EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:

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

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)

回答by kmario23

An alternative approach is to use numpy.resize()as in:

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