1. 程式人生 > >Python numpy 提取矩陣的某一行或某一列

Python numpy 提取矩陣的某一行或某一列

import numpy as np
a=np.arange(9).reshape(3,3)
a
Out[31]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

            矩陣的某一行

a[1]
Out[32]: array([3, 4, 5])

            矩陣的某一列

a[:,1]
Out[33]: array([1, 4, 7])
b=np.eye(3,3)

b
Out[36]: 
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]]
)

            把矩陣a的第2列賦值給矩陣b的第1列

b[:,0]=a[:,1]

b
Out[38]: 
array([[ 1.,  0.,  0.],
       [ 4.,  1.,  0.],
       [ 7.,  0.,  1.]])