Swapping columns in a numpy array?

There are two issues here. The first is that the data you pass to your function apparently isn’t a two-dimensional NumPy array — at least this is what the error message says.

The second issue is that the code does not do what you expect:

my_array = numpy.arange(9).reshape(3, 3)
# array([[0, 1, 2],
#        [3, 4, 5],
#        [6, 7, 8]])
temp = my_array[:, 0]
my_array[:, 0] = my_array[:, 1]
my_array[:, 1] = temp
# array([[1, 1, 2],
#        [4, 4, 5],
#        [7, 7, 8]])

The problem is that Numpy basic slicing does not create copies of the actual data, but rather a view to the same data. To make this work, you either have to copy explicitly

temp = numpy.copy(my_array[:, 0])
my_array[:, 0] = my_array[:, 1]
my_array[:, 1] = temp

or use advanced slicing

my_array[:, [0, 1]] = my_array[:, [1, 0]]

Leave a Comment