本文介绍了交换柱的numpy的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有 A = 1 B = 2 ,我可以写 A ,b = b,A A b 互换对方。

When I have a=1 and b=2, I can write a,b=b,a so that a and b are interchanged with each other.

我用这个矩阵数组:

   [ 1,  2,  0, -2]
   [ 0,  0,  1,  2]
   [ 0,  0,  0,  0]

交换一个numpy的阵列的列不起作用:

Swapping the columns of a numpy array does not work:

import numpy as np

x = np.array([[ 1,  2,  0, -2],
   [ 0,  0,  1,  2],
   [ 0,  0,  0,  0]])

x[:,1], x[:,2] = x[:,2], x[:,1]

它产生的:

   [ 1,  0,  0, -2]
   [ 0,  1,  1,  2]
   [ 0,  0,  0,  0]

所以 X [:1] 简直被覆盖,而不是转移到 X [:2]

So x[:,1] has simply been overwritten and not transferred to x[:,2].

为什么会出现这种情况?

Why is this the case?

推荐答案

如果你想换列可以通过

print x
x[:,[2,1]] = x[:,[1,2]]
print x

输出

[[ 1  2  0 -2]
 [ 0  0  1  2]
 [ 0  0  0  0]]
[[ 1  0  2 -2]
 [ 0  1  0  2]
 [ 0  0  0  0]]

你的问题中提到的交换方法似乎是工作单维数组和列表不过,

The swapping method you mentioned in the question seems to be working for single dimensional arrays and lists though,

x =  np.array([1,2,0,-2])
print x
x[2], x[1] = x[1], x[2]
print x

输出

[ 1  2  0 -2]
[ 1  0  2 -2]

这篇关于交换柱的numpy的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:22