Swapping Columns in a Numpy Array

Swapping Columns with NumPy arrays

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

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

output

[[ 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

output

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

Swap columns of an ndarray

This would do it:

b = a[:, [0, 2, 1]]

It works by providing a list of column indices in the second-dimension position. As always in Python, the indices are zero-based, so the first (leftmost) column is 0 and the third (rightmost, last) column is 2.

Python matrix swapping columns using numpy

Don't loop here, simply use 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]])

If you have a different order in mind, for example: 4, 3, 5, 2, 1, you can make use of advanced indexing:

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

How to swap array's columns if condition is satisfied

Here's one way with masking -

# Get 1D mask of length same as the column length of array and with True
# values at places where the combined sum is > 20
m = A[:,1] + A[:,2] > 20

# Get the masked elements off the second column
tmp = A[m,2]

# Assign into the masked places in the third col from the
# corresponding masked places in second col.
# Note that this won't change `tmp` because `tmp` isn't a view into
# the third col, but holds a separate memory space
A[m,2] = A[m,1]

# Finally assign into the second col from tmp
A[m,1] = tmp

Sample run -

In [538]: A
Out[538]:
array([[ 1, 2, 3],
[11, 12, 13],
[21, 22, 23]])

In [539]: m = A[:,1] + A[:,2] > 20
...: tmp = A[m,2]
...: A[m,2] = A[m,1]
...: A[m,1] = tmp

In [540]: A
Out[540]:
array([[ 1, 2, 3],
[11, 13, 12],
[21, 23, 22]])

Swap two rows in a numpy array in python

Put the index as a whole:

a[[x, y]] = a[[y, x]]

With your example:

a = np.array([[4,3,1], [5,7,0], [9,9,3], [8,2,4]])

a
# array([[4, 3, 1],
# [5, 7, 0],
# [9, 9, 3],
# [8, 2, 4]])

a[[0, 2]] = a[[2, 0]]
a
# array([[9, 9, 3],
# [5, 7, 0],
# [4, 3, 1],
# [8, 2, 4]])


Related Topics



Leave a reply



Submit