Swap columns in a NumPy array

How to swap or reorder columns in a NumPy array, why naive tuple swaps fail, when the result is a view or a copy, and what to check before exporting delimited text.

Swapping columns in a NumPy array looks like a one-line job, and usually it is. The method you pick still matters. Some approaches modify the array in place. Others return a new array. One common pattern quietly corrupts your data. This review covers what each approach changes, which one fits which job, and what to check when the reordered array ends up in a CSV or other delimited file.

Short recommendation

To exchange two columns in place, use fancy indexing on both sides of the assignment: arr[:, [i, j]] = arr[:, [j, i]]. It is short and correct, and it copies only the two columns involved. To put every column in a new order, index with a full permutation, arr[:, order], which returns a new array. Avoid swapping basic slices with tuple assignment, because both sides are views of the same memory.

Plain NumPy has one important limitation: an ordinary array has no column names. If your columns carry meaning through headers, such as a table you will export, review or share, positional swapping is easy to get wrong. In that case a labeled structure such as a pandas DataFrame, or a header list you reorder alongside the data, is the safer choice.

What a column swap actually changes

A column swap moves stored values to new positions. It is not a display effect. The numbers stay the same, but which values are found at which index changes, and every later step that refers to columns by position sees the new order. Where the result lives depends on how you index:

  • Fancy indexing (a list or array of indices) on the right-hand side always produces a copy.
  • Fancy indexing on the left-hand side writes into the original array in place.
  • Basic slicing (arr[:, 0] or arr[:, ::-1]) returns a view that shares memory with the original.
  • Reassigning a name (arr = arr[:, order]) creates a new array and leaves any other references pointing at the old one.

The reliable in-place swap

The right-hand side arr[:, [2, 0]] builds a temporary copy of columns 2 and 0. NumPy then writes that copy into positions 0 and 2. Because the source is a separate copy, the values cannot be overwritten partway through the assignment.

import numpy as np

arr = np.arange(9).reshape(3, 3)
# [[0 1 2]
#  [3 4 5]
#  [6 7 8]]

arr[:, [0, 2]] = arr[:, [2, 0]]
# [[2 1 0]
#  [5 4 3]
#  [8 7 6]]

Why the tuple-swap idiom fails

In Python, a, b = b, a is the usual way to swap two variables, so many people try the same thing with columns. With NumPy slices, this duplicates one column instead of exchanging the two.

arr = np.arange(9).reshape(3, 3)
arr[:, 0], arr[:, 2] = arr[:, 2], arr[:, 0]
# [[2 1 2]
#  [5 4 5]
#  [8 7 8]]

Here is what happens. The right-hand side evaluates to two views, not two copies. The first assignment overwrites column 0 with column 2. The second assignment then reads from the view of column 0, which now holds column 2's values. No error is raised, so the mistake can travel downstream unnoticed. If you prefer the tuple form, add .copy() to both right-hand items. The fancy-indexing form avoids the problem without that extra step.

Reordering more than two columns

For a full reorder, pass the new column order as an index list. The result is a new array, and the original is untouched unless you assign the result back to it.

arr = np.arange(9).reshape(3, 3)
reordered = arr[:, [2, 0, 1]]
# [[2 0 1]
#  [5 3 4]
#  [8 6 7]]

reversed_cols = arr[:, ::-1]   # view, not a copy
# [[2 1 0]
#  [5 4 3]
#  [8 7 6]]

Reversing column order with arr[:, ::-1] or np.flip(arr, axis=1) produces a view with negative strides. The view is cheap to create. However, writing to it changes the original array, and some code expects contiguous memory. Call np.ascontiguousarray or .copy() if you need an independent, contiguous result.

Which approach fits which situation

Goal | Approach | Result
Exchange two columns in place | arr[:, [i, j]] = arr[:, [j, i]] | Original modified
Arbitrary new column order | arr[:, order] | New array
Reverse column order | arr[:, ::-1] or np.flip(arr, axis=1) | View of original
Swap along the last axis of a 3-D or larger array | arr[..., [i, j]] = arr[..., [j, i]] | Original modified
Named columns that must stay matched to headers | Labeled structure such as a DataFrame, or reorder a header list in step | Depends on tool

Edge cases worth checking

  • One-dimensional arrays have no column axis, so arr[:, ...] raises an IndexError. Reshape the array first, or swap elements directly.
  • Negative indices work: arr[:, [0, -1]] = arr[:, [-1, 0]] swaps the first and last columns.
  • Structured arrays use field names instead of column positions. Multi-field indexing such as arr[['b', 'a']] returns a view in recent NumPy versions. Use numpy.lib.recfunctions.repack_fields if you need a compact reordered copy, and check the behavior against the documentation for your installed version.
  • Memory: a two-column swap copies only those two columns. A full reorder with fancy indexing copies the entire array. No benchmark figures were available for this review, so measure on your own data if size is a concern.

Will the result stay usable after export or sharing?

A NumPy array keeps no record of its original column order. The risk shows up when the data leaves NumPy as delimited text. np.savetxt writes values in the array's current order, and its header argument is a plain string that NumPy does not reconcile with the data. If you reorder the columns but not the header, the file reads cleanly but its labels are wrong. By default, savetxt also adds a comment marker before the header. Pass comments='' if the receiving tool expects a bare header row.

headers = ['a', 'b', 'c']
order = [2, 0, 1]
np.savetxt('out.csv', arr[:, order], delimiter=',',
           header=','.join(headers[k] for k in order), comments='')

Readers who open the exported file in a spreadsheet or text editor see ordinary delimited text. The swap does not affect copy and paste, screen readers or search the way visual text effects can, because only data positions change. The real usability question is whether anyone downstream relies on column position rather than names. If they do, document the new order or keep a version in the original order. This review found no destination-specific tests and makes no claims about how particular applications import the file.

Gaps in this review

No subject-specific evidence was supplied, such as performance measurements, version-by-version behavior tables or tests against named import tools. The behavior described here follows NumPy's documented indexing rules and the small examples shown. Before you rely on view versus copy behavior or structured-array field indexing in production, confirm it against your installed version's documentation.