np.squeeze()函数解析

版权声明:本文版权归作者和CSDN共有,欢迎转载。转载时请注明原作者并保留此段声明,若不保留我也不咬你,随你了=-=。 https://blog.csdn.net/TeFuirnever/article/details/88941254

np.squeeze()函数用于生成一个删除指定维度的数组。

np.squeeze(
	a,
	axis = None
	)

参数:

  • a表示输入的数组;
  • axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;axis的取值可为None 或 int 或 tuple of ints, 可选;若axis为空,则删除所有单维度的条目。

返回值:

一个已经删除指定维度的数组。

不会修改原数组

官方网站 https://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html

例子1:

import numpy as np

x = np.array([[[0], [1], [2]]])
print(x.shape)
print(x)
print(np.squeeze(x).shape)
print(np.squeeze(x))
print(np.squeeze(x, axis=0).shape)
print(np.squeeze(x, axis=0))
# print(np.squeeze(x, axis=1).shape)
print(np.squeeze(x, axis=2).shape)
print(np.squeeze(x, axis=2))
> (1, 3, 1)
> [[[0]
    [1]
    [2]]]
> (3,)
> [0 1 2]
> (3, 1)
> [[0]
   [1]
   [2]]
> (1, 3)
> [[0 1 2]]

这个例子中当运行下面代码时

print(np.squeeze(x, axis=1).shape)

会出现错误。

> ValueError: cannot select an axis to squeeze out which has size not equal to one

指定的维度不是单维度时,会报错。

例子2:

import numpy as np

c = np.arange(10).reshape(2,5)
print(c)
print(np.squeeze(c))
> [[0 1 2 3 4]
   [5 6 7 8 9]]
> [[0 1 2 3 4]
   [5 6 7 8 9]]

对非单维的维度使用np.squeeze()函数没有作用。

例子3:

import numpy as np

e = np.arange(10).reshape(1,10,1)
print(e)
print(np.squeeze(e).shape)
print(np.squeeze(e))
> [[[0]
    [1]
    [2]
    [3]
    [4]
    [5]
    [6]
    [7]
    [8]
    [9]]]
> (10,)
> [0 1 2 3 4 5 6 7 8 9]

当axis为空时,删除所有单维度的条目。

猜你喜欢

转载自blog.csdn.net/TeFuirnever/article/details/88941254