numpy中如何改变数据形态
arr = np.array([1,2,3])
升维
newaxis,
arr[np.newaxis,:]
==>
arr[None,:]
- 按行扩维
Run:
[[1,2,3]]
arr[:,newaxis]
==>
arr[:,None]
- 按列扩维
Run:
[[1],[2],[3]]
unsqueeze
np.unsqueeze()
降维
squeeze
np.squeeze(arr)
- 只能减少axis=1的维度
其他
reshape
arr.reshape(row,column)
- 将数组变为row行column列
ravel
arr.ravel()
- 将数组展平【变一维数组】
flatten
arr.flatten()
- 将数组展平
矩阵转置
transpose
np.transpose(arr)
==>
arr.T
- 将矩阵转置
拆解
vsplit
np.vsplit(arr,indices_or_sections)
-
横向切分
-
Example:
a = np.array( [[ 1, 11, 2, 22], [ 3, 33, 4, 44], [ 5, 55, 6, 66], [ 7, 77, 8, 88]] ) print(np.vsplit(a, indices_or_sections=2))
Run:
[array([[ 1, 11, 2, 22],
[ 3, 33, 4, 44]]),array([[ 5, 55, 6, 66],
[ 7, 77, 8, 88]])]
hsplit
np.hsplit()
- 纵向切分
split
np.split(arr,indices_or_section,axis)
-
自定义切分
-
Example:
a = np.array( [[ 1, 11, 2, 22], [ 3, 33, 4, 44], [ 5, 55, 6, 66], [ 7, 77, 8, 88]] ) print(np.split(a, indices_or_sections=2, axis=0)) # 分成两段 print(np.split(a, indices_or_sections=[2,3], axis=1)) # 在第二维度, 0~2 一段,2~3 一段,3~一段
Run:
[array([[ 1, 11, 2, 22],
[ 3, 33, 4, 44]]), array([[ 5, 55, 6, 66],
[ 7, 77, 8, 88]])][array([[ 1, 11],
[ 3, 33],
[ 5, 55],
[ 7, 77]]), array([[2],
[4],
[6],
[8]]), array([[22],
[44],
[66],
[88]])][2,3]这是拆分位置[0-2),[2-3),[3-len)