文章目錄
測試代碼
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)