矩阵转置和重构
In:
#NumPy数组的属性T可用于获取矩阵的转置
print('转置前:
',data12)
print('转置后:
',data12.T)转置前:
[[1 2]
[3 4]
[5 6]]
转置后:
[[1 3 5]
[2 4 6]]
In:
#在较为复杂的用例中,可能需要使用NumPy的reshape()方法改变某个矩阵的维度
data13 = np.array([1,2,3,4,5,6])
print('重构前:
',data13)
print('重构后:
',data13.reshape(2,3))
print('重构后:
',data13.reshape(3,2))
Out:
重构前:
[1 2 3 4 5 6]
重构后:
[[1 2 3]
[4 5 6]]
重构后:
[[1 2]
[3 4]
[5 6]]
In:
#上文中的所有功能都适用于多维数据,其中心数据结构称为ndarray(N维数组)
data14 = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
print(data14)
print('-'*20)
#改变维度只需在NumPy函数的参数中添加一个逗号和维度
print(np.ones((4,3,2)))
print('-'*20)
print(np.zeros((4,3,2)))
print('-'*20)
print(np.random.random((4,3,2)))
Out:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
--------------------
[[[1. 1.]
[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]
[1. 1.]]]
--------------------
[[[0. 0.]
[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]
[0. 0.]]]
--------------------
[[[0.37593802 0.42651876]
[0.74639264 0.19783467]
[0.787414 0.63820259]]
[[0.84871262 0.46467497]
[0.54633954 0.4376995 ]
[0.71988166 0.9306682 ]]
[[0.6384108 0.74196991]
[0.73857164 0.38450555]
[0.68579442 0.64018511]]
[[0.60382775 0.35889667]
[0.8625612 0.86523028]
[0.83701853 0.08289658]]]