Python 使用 numpy 矩阵交换列
Python matrix swapping columns using numpy
这是我的 Y 矩阵,我正在尝试交换列(使列 [1,2,3,4,5] 代替 [5,4,3,2,1])
但是,这会改变数字的准确性
这是 Y
> array([[ 0.0e+00, 1.0e-15, 0.0e+00, 0.0e+00, 0.0e+00],
> [ 1.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00],
> [-1.0e-02, 1.2e-02, 0.0e+00, 0.0e+00, 0.0e+00],
> [ 1.0e-02, -1.0e-02, 1.0e+00, 0.0e+00, 0.0e+00]])
这是代码
y1, y2= np.shape(Y)
y2= y2-2
for row in range (y1):
for column in range (y2):
Z[row, column]=Y[row, y2-column+1]
这是Z
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.]])
如何使它具有相同的精度?
这里不要循环,直接用np.flip
x = np.array([[ 0.0e+00, 1.0e-15, 0.0e+00, 0.0e+00, 0.0e+00],
[ 1.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00],
[-1.0e-02, 1.2e-02, 0.0e+00, 0.0e+00, 0.0e+00],
[ 1.0e-02, -1.0e-02, 1.0e+00, 0.0e+00, 0.0e+00]])
np.flip(x, axis=1)
array([[ 0.0e+00, 0.0e+00, 0.0e+00, 1.0e-15, 0.0e+00],
[ 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 1.0e+00],
[ 0.0e+00, 0.0e+00, 0.0e+00, 1.2e-02, -1.0e-02],
[ 0.0e+00, 0.0e+00, 1.0e+00, -1.0e-02, 1.0e-02]])
如果您有不同的顺序,例如:4, 3, 5, 2, 1
,您可以使用高级索引:
x[:, [3, 2, 4, 1, 0]]
array([[ 0.0e+00, 0.0e+00, 0.0e+00, 1.0e-15, 0.0e+00],
[ 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 1.0e+00],
[ 0.0e+00, 0.0e+00, 0.0e+00, 1.2e-02, -1.0e-02],
[ 0.0e+00, 1.0e+00, 0.0e+00, -1.0e-02, 1.0e-02]])
这是我的 Y 矩阵,我正在尝试交换列(使列 [1,2,3,4,5] 代替 [5,4,3,2,1]) 但是,这会改变数字的准确性
这是 Y
> array([[ 0.0e+00, 1.0e-15, 0.0e+00, 0.0e+00, 0.0e+00],
> [ 1.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00],
> [-1.0e-02, 1.2e-02, 0.0e+00, 0.0e+00, 0.0e+00],
> [ 1.0e-02, -1.0e-02, 1.0e+00, 0.0e+00, 0.0e+00]])
这是代码
y1, y2= np.shape(Y)
y2= y2-2
for row in range (y1):
for column in range (y2):
Z[row, column]=Y[row, y2-column+1]
这是Z
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.]])
如何使它具有相同的精度?
这里不要循环,直接用np.flip
x = np.array([[ 0.0e+00, 1.0e-15, 0.0e+00, 0.0e+00, 0.0e+00],
[ 1.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00],
[-1.0e-02, 1.2e-02, 0.0e+00, 0.0e+00, 0.0e+00],
[ 1.0e-02, -1.0e-02, 1.0e+00, 0.0e+00, 0.0e+00]])
np.flip(x, axis=1)
array([[ 0.0e+00, 0.0e+00, 0.0e+00, 1.0e-15, 0.0e+00],
[ 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 1.0e+00],
[ 0.0e+00, 0.0e+00, 0.0e+00, 1.2e-02, -1.0e-02],
[ 0.0e+00, 0.0e+00, 1.0e+00, -1.0e-02, 1.0e-02]])
如果您有不同的顺序,例如:4, 3, 5, 2, 1
,您可以使用高级索引:
x[:, [3, 2, 4, 1, 0]]
array([[ 0.0e+00, 0.0e+00, 0.0e+00, 1.0e-15, 0.0e+00],
[ 0.0e+00, 0.0e+00, 0.0e+00, 0.0e+00, 1.0e+00],
[ 0.0e+00, 0.0e+00, 0.0e+00, 1.2e-02, -1.0e-02],
[ 0.0e+00, 1.0e+00, 0.0e+00, -1.0e-02, 1.0e-02]])