交换数组中的元素
Swaping elements in an array
我得到了下面的 numpy 数组:
a = np.array([
[ 0.87142134, -1.99712722, -0.17742774],
[-0.15155389, 0.0450012 , 0.23662928],
[-0.84674329, 2.34415168, 1.23702494],
[ 1.98923065, -0.02327895, 0.21864032],
[ 1.62936827, 1.39849021, 1.04613713]])
我想交换位置 0 和位置 1 之间的值,就像这样:
array([[-1.99712722, 0.87142134, -0.17742774],
[0.0450012, -0.15155389, 0.23662928],
[2.34415168, -0.84674329, 1.23702494],
[-0.02327895, 1.98923065, 0.21864032],
[1.39849021, 1.62936827, 1.04613713]])
我尝试了如下代码,但是失败了:
b = a.T
b[1], b[0] = b[0], b[1]
我怎样才能达到这个结果?
您可以使用:
a[:, [0,1]] = a[:, [1,0]]
输出:
array([[-1.99712722, 0.87142134, -0.17742774],
[ 0.0450012 , -0.15155389, 0.23662928],
[ 2.34415168, -0.84674329, 1.23702494],
[-0.02327895, 1.98923065, 0.21864032],
[ 1.39849021, 1.62936827, 1.04613713]])
我得到了下面的 numpy 数组:
a = np.array([
[ 0.87142134, -1.99712722, -0.17742774],
[-0.15155389, 0.0450012 , 0.23662928],
[-0.84674329, 2.34415168, 1.23702494],
[ 1.98923065, -0.02327895, 0.21864032],
[ 1.62936827, 1.39849021, 1.04613713]])
我想交换位置 0 和位置 1 之间的值,就像这样:
array([[-1.99712722, 0.87142134, -0.17742774],
[0.0450012, -0.15155389, 0.23662928],
[2.34415168, -0.84674329, 1.23702494],
[-0.02327895, 1.98923065, 0.21864032],
[1.39849021, 1.62936827, 1.04613713]])
我尝试了如下代码,但是失败了:
b = a.T
b[1], b[0] = b[0], b[1]
我怎样才能达到这个结果?
您可以使用:
a[:, [0,1]] = a[:, [1,0]]
输出:
array([[-1.99712722, 0.87142134, -0.17742774],
[ 0.0450012 , -0.15155389, 0.23662928],
[ 2.34415168, -0.84674329, 1.23702494],
[-0.02327895, 1.98923065, 0.21864032],
[ 1.39849021, 1.62936827, 1.04613713]])