答案是访问数组的.shape属性。该属性返回一个元组,表示数组在各维度上的大小,例如一维数组为(元素个数,),二维数组为(行数, 列数),三维数组为(深度, 行数, 列数),且其长度等于数组维度ndim,是数据处理中进行校验、优化和操作的核心依据。

在Python中,要获取NumPy数组的形状(shape),最直接且常用的方式就是访问数组对象的
.shape
获取NumPy数组形状的核心方法是使用其内置的
.shape
例如,一个二维数组的
shape
(行数, 列数)
(深度, 行数, 列数)
import numpy as np
# 1D 数组
arr_1d = np.array([1, 2, 3, 4, 5])
print(f"arr_1d 的形状: {arr_1d.shape}") # 输出: (5,)
# 2D 数组
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(f"arr_2d 的形状: {arr_2d.shape}") # 输出: (2, 3)
# 3D 数组
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(f"arr_3d 的形状: {arr_3d.shape}") # 输出: (2, 2, 2)
# 标量(0维数组)
scalar_arr = np.array(10)
print(f"scalar_arr 的形状: {scalar_arr.shape}") # 输出: ()除了直接访问
.shape
np.shape()
.shape
立即学习“Python免费学习笔记(深入)”;
# 使用 np.shape()
list_data = [[10, 20], [30, 40]]
print(f"list_data 的形状 (通过 np.shape()): {np.shape(list_data)}") # 输出: (2, 2)
# 与 arr_2d.shape 结果一致
print(f"arr_2d 的形状 (通过 np.shape()): {np.shape(arr_2d)}") # 输出: (2, 3)这确实是初学者,甚至有时是我自己,在处理NumPy数组时容易混淆的一个点。简单来说,
ndim
shape
举个例子,想象一个表格,它有行和列。这个表格就是二维的,所以它的
ndim
shape
(5, 3)
[1, 2, 3]
ndim
shape
(3,)
从技术角度讲,
ndim
len(arr.shape)
shape
ndim
shape
ndim
shape
解读
shape
ndim=1
shape
(5,)
arr = np.array([10, 20, 30]) print(arr.shape) # 输出: (3,)
ndim=2
shape
(行数, 列数)
arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr.shape) # 输出: (2, 3) - 2行3列
ndim=3
shape
(深度, 行数, 列数)
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) print(arr.shape) # 输出: (2, 2, 2) - 2个2x2的矩阵
shape
shape
ValueError: operands could not be broadcast together with shapes (X, Y) (A, B)
shape
理解并能够正确获取和解读NumPy数组的
shape
数据校验与错误预防: 在处理外部数据或进行多步数据转换时,我经常会检查数组的
shape
(batch_size, features)
(features, batch_size)
transpose
shape
shape
内存管理与性能优化: NumPy数组是内存连续存储的,其
shape
shape
(10000, 10000)
float64
shape
shape
高效的数组操作: NumPy的强大之处在于其向量化操作。很多操作都是基于数组的
shape
shape
shape
shape
算法设计与实现: 在设计图像处理、信号处理或机器学习算法时,数据通常以多维数组的形式存在。算法的每一步操作,比如卷积、池化、矩阵乘法,都对输入数组的
shape
shape
reshape
stack
shape
以上就是Python怎么获取NumPy数组的形状(shape)_NumPy数组维度与形状查询的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号