从 NumPy 数组中移除长度为一的轴
使用 Python NumPy 中的 **numpy.squeeze()** 方法压缩数组形状。这将从数组中移除长度为一的轴。该函数返回输入数组,但移除所有或一部分长度为 1 的维度。这始终是数组本身或输入数组的视图。如果所有轴都被压缩,则结果为一个 0 维数组,而不是标量。
轴选择形状中长度为一的条目子集。如果选择的轴的形状条目大于 1,则会引发错误。
步骤
首先,导入所需的库 -
import numpy as np
使用 array() 方法创建一个 NumPy 数组。我们添加了 int 类型的元素 -
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() 方法压缩数组形状 -
print("
Squeeze the shape of Array...
",np.squeeze(arr).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
print("
Squeeze the shape of Array...
",np.squeeze(arr).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)
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP