移除NumPy数组中长度为一的轴(沿轴0)
使用**numpy.squeeze()**方法压缩数组形状。这将移除数组中长度为一的轴。轴由“axis”参数设置。这里我们将axis设置为0。
该函数返回输入数组,但移除所有或一部分长度为1的维度。这始终是数组本身或输入数组的视图。如果所有轴都被压缩,结果将是一个0维数组,而不是标量。
axis参数选择形状中长度为一的条目子集。如果选择的轴的形状条目大于一,则会引发错误。
步骤
首先,导入所需的库:
import numpy as np
使用array()方法创建一个NumPy数组。我们添加了整型元素:
arr = np.array([[[20, 36, 57, 78], [32, 54, 69, 84]]])
显示数组:
print("Our Array...
",arr)检查维度:
print("
Dimensions of our Array...
",arr.ndim)
获取数据类型:
print("
Datatype of our Array object...
",arr.dtype)显示数组的形状:
print("
Array Shape...
",arr.shape)
使用numpy.squeeze()方法压缩数组形状。轴由“axis”参数设置:
print("
Squeeze the shape of Array...
",np.squeeze(arr, axis = 0).shape)示例
import numpy as np
# Creating a numpy array using the array() method
# We have added elements of int type
arr = np.array([[[20, 36, 57, 78], [32, 54, 69, 84]]])
# Display the array
print("Our Array...
",arr)
# Check the Dimensions
print("
Dimensions of our Array...
",arr.ndim)
# Get the Datatype
print("
Datatype of our Array object...
",arr.dtype)
# Display the shape of array
print("
Array Shape...
",arr.shape)
# Squeeze the Array shape using the numpy.squeeze() method
# The axis is set using the "axis" parameter
print("
Squeeze the shape of Array...
",np.squeeze(arr, axis = 0).shape)输出
Our Array... [[[20 36 57 78] [32 54 69 84]]] Dimensions of our Array... 3 Datatype of our Array object... int64 Array Shape... (1, 2, 4) Squeeze the shape of Array... (2, 4)
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP