python - 交换数组中的元素

标签 python arrays numpy swap

我得到了下面的 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]])

关于python - 交换数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72184263/

相关文章:

python - 格式化 sql %like%

python - 无法在 docker 容器内加载动态库 'libcudart.so.11.0'

c - struct数组元素初始化

java - Clojure into-array 遍历数组

python - SciPy + Numpy : Finding the slope of a sigmoid curve

python - 沿 numpy 数组给定轴的所有切片的总和

python - 规范化 Python 中的数字列表

python - 缓存一个常量值

c - GCC 是如何实现变长数组的?

python - python中循环的向量化