Numpy库基础___二
ndarray一个强大的N维数组对象Array
•ndarray的变换
- x.reshape(shape)重塑数组的shape,要求元素的个数一致,不改变原数组
x = np.ones((2,3,4),dtype=np.int32) print(x) #[[[1 1 1 1] # [1 1 1 1] # [1 1 1 1]] # # [[1 1 1 1] # [1 1 1 1] # [1 1 1 1]]] #[[[1 1 1 1] # [1 1 1 1] # [1 1 1 1]] # # [[1 1 1 1] # [1 1 1 1] # [1 1 1 1]]] a = x.reshape((3,8)) print(a) #[[1 1 1 1 1 1 1 1] # [1 1 1 1 1 1 1 1] # [1 1 1 1 1 1 1 1]]
- x .resize(shape)和x.reshape(shape)功能一样,但修改原数组
只有resize会改变原数组!
x = np.ones((2,3,4),dtype=np.int32) print(x) #[[[1 1 1 1] # [1 1 1 1] # [1 1 1 1]] # [[1 1 1 1] # [1 1 1 1] # [1 1 1 1]]] a = x.resize((3,8)) print(x) #[[1 1 1 1 1 1 1 1] # [1 1 1 1 1 1 1 1] # [1 1 1 1 1 1 1 1]] print(a) #None
- x.swapaxes(a,b)将数组中n个维度中的两个维度调换
x = np.ones((2,3,4),dtype=np.int32) print(x) # [[[1 1 1 1] # [1 1 1 1] # [1 1 1 1]] # # [[1 1 1 1] # [1 1 1 1] # [1 1 1 1]]] x = x.swapaxes(0,2) print(x) #[[[1 1] # [1 1] # [1 1]] # # [[1 1] # [1 1] # [1 1]] # # [[1 1] # [1 1] # [1 1]] # # [[1 1] # [1 1] # [1 1]]]
- x.transpose(shape)矩阵x按照shape转置
x = np.ones((2,3,4),dtype=np.int32) print(x) #[[[1 1 1 1] # [1 1 1 1] # [1 1 1 1]] # # [[1 1 1 1] # [1 1 1 1] # [1 1 1 1]]] x = x.transpose((2,1,0)) print(x) [[[1 1] # [1 1] # [1 1]] # # [[1 1] # [1 1] # [1 1]] # # [[1 1] # [1 1] # [1 1]] # # [[1 1] # [1 1] # [1 1]]]