NumPy -数组属性与形状操作
数组属性与形状操作
目录
- 数组属性
- 形状操作
- 维度操作
- 转置操作
- 实际应用示例
数组属性
基本属性
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])print(f"数组:\n{arr}")
print(f"形状 (shape): {arr.shape}") # (3, 3)
print(f"维度 (ndim): {arr.ndim}") # 2
print(f"大小 (size): {arr.size}") # 9
print(f"数据类型 (dtype): {arr.dtype}") # int64
print(f"元素大小 (itemsize): {arr.itemsize}") # 8 字节
print(f"总内存 (nbytes): {arr.nbytes}") # 72 字节
print(f"标志 (flags):\n{arr.flags}")
数据访问属性
import numpy as nparr = np.array([1, 2, 3, 4, 5])# 数据指针
print(f"数据指针: {arr.ctypes.data}")# 数据是否连续存储
print(f"是否连续: {arr.flags['C_CONTIGUOUS']}")# 是否只读
arr_readonly = arr.copy()
arr_readonly.flags.writeable = False
print(f"是否只读: {arr_readonly.flags['WRITEABLE']}")
形状操作
reshape 方法
import numpy as np# 创建一维数组
arr = np.arange(12)
print(f"原数组: {arr}")
print(f"形状: {arr.shape}")# 重塑为二维数组
arr_2d = arr.reshape(3, 4)
print(f"\n重塑为 (3, 4):\n{arr_2d}")# 重塑为三维数组
arr_3d = arr.reshape(2, 2, 3)
print(f"\n重塑为 (2, 2, 3):\n{arr_3d}")# 使用 -1 自动计算维度
arr_auto = arr.reshape(3, -1)
print(f"\n自动计算列数:\n{arr_auto}")# 一维化
arr_flat = arr_2d.reshape(-1)
print(f"\n一维化: {arr_flat}")
resize 方法
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"原数组:\n{arr}")# resize 会修改原数组
arr.resize(3, 2)
print(f"\nresize 后:\n{arr}")# 如果新大小更大,用0填充
arr.resize(4, 3)
print(f"\n扩大后(用0填充):\n{arr}")
flatten 和 ravel 方法
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"原数组:\n{arr}")# flatten:返回副本
arr_flat1 = arr.flatten()
arr_flat1[0] = 999
print(f"\nflatten (修改后):\n{arr_flat1}")
print(f"原数组未变:\n{arr}")# ravel:返回视图(如果可能)
arr_flat2 = arr.ravel()
arr_flat2[0] = 888
print(f"\nravel (修改后):\n{arr_flat2}")
print(f"原数组已变:\n{arr}")
维度操作
增加维度
import numpy as nparr = np.array([1, 2, 3, 4])
print(f"原数组: {arr}")
print(f"形状: {arr.shape}")# 使用 newaxis 增加维度
arr_row = arr[np.newaxis, :]
print(f"\n行向量:\n{arr_row}")
print(f"形状: {arr_row.shape}")arr_col = arr[:, np.newaxis]
print(f"\n列向量:\n{arr_col}")
print(f"形状: {arr_col.shape}")# 使用 expand_dims
arr_expanded = np.expand_dims(arr, axis=0)
print(f"\nexpand_dims (axis=0):\n{arr_expanded}")
print(f"形状: {arr_expanded.shape}")arr_expanded = np.expand_dims(arr, axis=1)
print(f"\nexpand_dims (axis=1):\n{arr_expanded}")
print(f"形状: {arr_expanded.shape}")
减少维度
import numpy as nparr = np.array([[[1, 2, 3]]])
print(f"原数组: {arr}")
print(f"形状: {arr.shape}")# squeeze:移除长度为1的维度
arr_squeezed = np.squeeze(arr)
print(f"\nsqueeze 后: {arr_squeezed}")
print(f"形状: {arr_squeezed.shape}")# 指定 axis
arr2 = np.array([[[1]], [[2]], [[3]]])
print(f"\n原数组形状: {arr2.shape}")
arr2_squeezed = np.squeeze(arr2, axis=2)
print(f"squeeze (axis=2) 后形状: {arr2_squeezed.shape}")
转置操作
transpose 方法
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"原数组:\n{arr}")
print(f"形状: {arr.shape}")# 转置
arr_T = arr.T
print(f"\n转置:\n{arr_T}")
print(f"形状: {arr_T.shape}")# 使用 transpose 方法
arr_T2 = arr.transpose()
print(f"\n使用 transpose:\n{arr_T2}")# 多维数组转置
arr_3d = np.arange(24).reshape(2, 3, 4)
print(f"\n三维数组形状: {arr_3d.shape}")# 交换轴
arr_T3d = arr_3d.transpose(2, 0, 1)
print(f"转置后形状: {arr_T3d.shape}")
swapaxes 方法
import numpy as nparr = np.arange(24).reshape(2, 3, 4)
print(f"原数组形状: {arr.shape}")# 交换轴
arr_swapped = np.swapaxes(arr, 0, 2)
print(f"交换轴 0 和 2 后形状: {arr_swapped.shape}")arr_swapped = np.swapaxes(arr, 1, 2)
print(f"交换轴 1 和 2 后形状: {arr_swapped.shape}")
moveaxis 方法
import numpy as nparr = np.arange(24).reshape(2, 3, 4)
print(f"原数组形状: {arr.shape}")# 移动轴
arr_moved = np.moveaxis(arr, 0, -1)
print(f"移动轴 0 到最后: {arr_moved.shape}")arr_moved = np.moveaxis(arr, [0, 1], [1, 0])
print(f"交换轴 0 和 1: {arr_moved.shape}")
实际应用示例
示例 1:图像处理中的形状操作
import numpy as np# 模拟图像数据 (高度, 宽度, 通道)
image = np.random.randint(0, 255, size=(480, 640, 3), dtype=np.uint8)
print(f"原始图像形状: {image.shape}")# 转换为灰度图(简单平均)
gray = image.mean(axis=2).astype(np.uint8)
print(f"灰度图形状: {gray.shape}")# 调整大小(下采样)
small = gray[::2, ::2]
print(f"下采样后形状: {small.shape}")# 重塑为一维特征向量
features = small.flatten()
print(f"特征向量形状: {features.shape}")
示例 2:矩阵运算中的形状操作
import numpy as np# 创建数据矩阵
data = np.random.randn(100, 10)
print(f"数据矩阵形状: {data.shape}")# 添加偏置项(需要在每行前加1)
bias = np.ones((100, 1))
data_with_bias = np.concatenate([bias, data], axis=1)
print(f"添加偏置后形状: {data_with_bias.shape}")# 转置用于矩阵乘法
data_T = data_with_bias.T
print(f"转置后形状: {data_T.shape}")# 计算协方差矩阵(需要中心化)
data_centered = data - data.mean(axis=0)
cov_matrix = np.dot(data_centered.T, data_centered) / (data.shape[0] - 1)
print(f"协方差矩阵形状: {cov_matrix.shape}")
示例 3:批量数据处理
import numpy as np# 创建批次数据
batch_size = 32
features = np.random.randn(1000, 784) # 1000个样本,每个784维特征
print(f"原始数据形状: {features.shape}")# 重塑为批次
num_batches = features.shape[0] // batch_size
features_batched = features[:num_batches * batch_size].reshape(num_batches, batch_size, 784)
print(f"批次数据形状: {features_batched.shape}")# 处理每个批次
for i, batch in enumerate(features_batched):print(f"批次 {i}: 形状 {batch.shape}")# 这里可以进行批量处理
总结
数组属性与形状操作要点:
- 属性:shape, ndim, size, dtype, itemsize, nbytes
- 形状操作:reshape, resize, flatten, ravel
- 维度操作:newaxis, expand_dims, squeeze
- 转置操作:T, transpose, swapaxes, moveaxis
