Numpy中数组与矩阵的转换

数组转为矩阵以及矩阵转为数组的方法

代码:


import numpy as np
from numpy import mat

# 产生一个数组为[1 2 3 4],左闭右开,step=1
x = np.arange(1, 5, 1)
# 将x转换为矩阵
X = mat(x).reshape(2, 2)

# 产生一个2*5的矩阵
Y = mat(np.arange(1, 11, 1).reshape(2, 5))
# 将该矩阵转换为数组
y = Y.getA()

print("x: " + str(x) + ", type:" + str(type(x)))
print("X: " + str(X) + ", type:" + str(type(X)))

print("Y: " + str(Y) + ", type:" + str(type(Y)))
print("y: " + str(y) + ", type:" + str(type(y)))

输出:
x: [1 2 3 4], type:<class 'numpy.ndarray'>
X: [[1 2]
 [3 4]], type:<class 'numpy.matrix'>
Y: [[ 1  2  3  4  5]
 [ 6  7  8  9 10]], type:<class 'numpy.matrix'>
y: [[ 1  2  3  4  5]
 [ 6  7  8  9 10]], type:<class 'numpy.ndarray'>

Process finished with exit code 0

你可能感兴趣的:(Python,python,numpy)