高级数组操作全解析
在数组处理中,除了高级索引、切片和布尔子集操作外,还有许多其他实用的方法。下面将详细介绍数组重塑、排序顺序、拼接与拆分、元素重复、花式索引替代方法、广播以及通用函数的高级用法等内容。
1. 数组重塑
数组重塑是指在不复制数据的情况下,将数组从一种形状转换为另一种形状。可以通过将表示新形状的元组传递给数组实例方法 reshape 来实现。
import numpy as np
# 将一维数组重塑为矩阵
arr = np.arange(8)
print("原始一维数组:", arr)
reshaped_arr = arr.reshape((4, 2))
print("重塑后的二维数组:\n", reshaped_arr)
# 多维数组的重塑
reshaped_again = reshaped_arr.reshape((2, 4))
print("再次重塑后的二维数组:\n", reshaped_again)
# 可以使用 -1 让维度自动推断
arr = np.arange(15)
inferred_arr = arr.reshape((5, -1))
print("使用 -1 推断维度后的数组:\n", inferred_arr)
# 也可以使用另一个数组的 shape 属性进行重塑
other_arr = np.ones((3, 5))
reshaped_with_shape = arr.reshape(other_arr.shape)
print("使用其他数组 shape 属性重塑后的数组:\n", reshaped_with_shape)
# 扁平化操作
超级会员免费看
订阅专栏 解锁全文
702

被折叠的 条评论
为什么被折叠?



