用 NumPy 数组交换列 [英] Swapping Columns with NumPy arrays

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

问题描述

当我有 a=1b=2 时,我可以写 a,b=b,a 以便 ab 可以互换.

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].

为什么会这样?

推荐答案

如果你想交换列,你可以这样做

If you're trying to swap columns you can do it by

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 数组交换列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆