python学习笔记——矩阵跟向量间的转换

1、 矩阵转向量:ravel()flatten()函数可以实现多维数据向一维数据转换
import numpy as np
x = np.arange(9).reshape(3,3)
print(type(x),x.shape)
print(x)

x = x.reshape(1,9)
print(type(x),x.shape)
print(x)

a = x.ravel()
print(type(a),a.shape)
print(a)
b = x.flatten()
print(b)

a[1]=100
print(a)
b[1]=100
print(b)
..............................
 (3, 3)
[[0 1 2]
 [3 4 5]
 [6 7 8]]

 (1, 9)
[[0 1 2 3 4 5 6 7 8]]

 (9,)
[0 1 2 3 4 5 6 7 8]
[0 1 2 3 4 5 6 7 8]

[  0 100   2   3   4   5   6   7   8]
[  0 100   2   3   4   5   6   7   8]

2、向量转矩阵:reshape() 可以将一维数据转为多维数据

import numpy as np
x = np.arange(10)
print(type(x),x.shape)
print(x)

a = x.reshape(1,10)
print(type(a),a.shape)
print(a)

b = x.reshape(5,2)
print(type(b),b.shape)
print(b)

b = x.reshape(2,5)
print(type(b),b.shape)
print(b)
.......................
 (10,)
[0 1 2 3 4 5 6 7 8 9]
 (1, 10)
[[0 1 2 3 4 5 6 7 8 9]]
 (5, 2)
[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]
 (2, 5)
[[0 1 2 3 4]
 [5 6 7 8 9]]

你可能感兴趣的:(python,学习,矩阵)