文章目录
测试代码
import numpy as np
arr = np.array(
[[1, 2, 7],
[4, 1, 6],
[7, 8, 9],
[ 0, 0, 0]]
)
print(arr)
print("*"*15)
修改数组形状
reshape
数据不改变修改数组形状
np.reshape(arr, newshape, order=‘C’)
arr = np.reshape(arr,(3,4))
print(arr)
resize
可以改变数据同时也能修改数组形状
np.resize(arr, shape)
arr = np.resize(arr,(3,4))
print(arr)
print("*"*15)
arr = np.resize(arr,(2,5))
print(arr)
注意
reshape修改的形状必须要能够容纳原先所有元素,元素不能修改,否则报错
而resize没有要求,会自动删减元素来适应新改变的形状
修改数组维度
squeeze
从数组的形状中删除一个维度
np.squeeze(arr, axis)
分割数组
split
将数组按照指定条件切割
split(ary, indices_or_sections, axis=0)
参数 | 作用 |
---|---|
ary | 要求切割数组 |
indices_or_sections | 传入整数,按整数将原数组均分成整数个小数组,传入指定数组,则以指定数组为分割线分割 |
axis=0 | 默认横向切割,1则纵向切割 |
# 分成4行
arr = np.split(arr, 4, axis=0)
print(arr)
# 以[2,1,8,0]分割
arr = np.split(arr, [4, 1, 6])
print(arr)
hsplit
水平分割
np.hsplit(ary, indices_or_sections)
vsplit
垂直分割
np.vsplit(ary, indices_or_sections)
连接数组
stack
拼接
np.stack(arrays, axis=0, out=None)
传入axis用于指定拼接方向
hstack
水平拼接
import numpy as np
arr1 = np.array(
[[1, 2, 7],
[4, 1, 6],
[7, 8, 9],]
)
arr2 = np.array(
[[1, 2, 7],
[4, 1, 6],
[7, 8, 9],]
)
# 水平拼接
arr = np.hstack((arr1,arr2))
print(arr)
vstack
竖直拼接
# 竖直拼接
arr = np.vstack((arr1,arr2))
print(arr)
数组转置
transpose
将数组维度调换
import numpy as np
arr = np.array(
[[1, 2, 7],
[4, 1, 6],
[7, 8, 9],
[0, 0, 0]]
)
print(arr)
print("*"*15)
arr = np.transpose(arr)
print(arr)
rollaxis
向后滚动指定的轴
swapaxes
交换数组的轴
import numpy as np
# 三维数组
arr = np.array(
[[[1, 2, 7],
[4, 1, 6]],
[[7, 8, 9],
[0, 0, 0]]]
)
print(arr)
print(arr.shape)
print("*"*15)
arr = np.swapaxes(arr,0,2)
print(arr)
print(arr.shape)
数组行列交换
通过切片操作来实现行或者列的交换
import numpy as np
# 三维数组
arr = np.array(
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
)
print(arr)
print("*"*15)
# 交换第一行和第二行
arr[[0,1],:] = arr[[1,0],:]
print(arr)
# 交换第一列和第二列
arr[:,[0,1]] = arr[:,[1,0]]
print(arr)