How to Swap Odd and Even Columns in a Pandas DataFrame
Learn multiple techniques to interchange odd‑ and even‑positioned columns in a pandas DataFrame—including reshaping with NumPy, column indexing tricks, and handling both even and odd numbers of columns—complete with code examples and explanations for flexible data manipulation.
Rescuing pandas (16) – Swapping Odd and Even Columns in a DataFrame
Many users avoid pandas for data manipulation, so this tutorial shows how to make pandas more appealing by swapping the positions of odd‑ and even‑indexed columns.
Data Requirement
The task, posed by a community member, is to exchange column A with B, C with D, etc. For an even number of columns this is straightforward; the article also covers the more complex case of an odd number of columns.
import pandas as pd
en = 'abcdefg'
df = pd.DataFrame(([i + j for j in en] for i in en), columns=list(en.upper()), index=list(en.upper()))Target layout: adjacent odd‑even column pairs should swap, while the final column G remains unchanged if it has no partner.
Requirement Breakdown
First treat the DataFrame as if it had an even number of columns, then handle the odd‑column case separately.
Processing Even‑Column DataFrames
import pandas as pd
en = 'abcdef'
df = pd.DataFrame(([i + j for j in en] for i in en), columns=list(en.upper()), index=list(en.upper()))Using NumPy, extract odd and even columns, stack them into a 2×n array, and flatten column‑wise:
import numpy as np
odd_c = df.columns[::2] # odd columns
even_c = df.columns[1::2] # even columns
# Stack with even columns on top, then flatten column‑wise
new_c = np.array((even_c, odd_c)).flatten('F')
print(df[new_c])Another approach reshapes the column values into a 2×n matrix and then flattens:
new_c = df.columns.values.reshape((2, len(df.columns) // 2), order='F')Flipping the rows and flattening also achieves the swap:
df[new_c[::-1].flatten('F')]Using the power of (‑1)ⁱ, a concise list comprehension swaps adjacent columns:
new_c = [df.columns[i + (-1) ** i for i in range(len(df.columns))]
# ['B', 'A', 'D', 'C', 'F', 'E']
df[new_c]Handling an Odd Number of Columns
When the column count is odd, separate the last column, apply the even‑column method to the rest, then append the final column back:
import numpy as np
c = df.columns.values
c_ = c[:-1] # all but last column
c_last = c[-1] # last column
c_new_even = c_.reshape((2, len(c_) // 2), order='F')[::-1].flatten('F')
new_c = np.hstack([c_new_even, c_last])A more generic solution works for both even and odd column counts by dynamically determining whether a trailing column exists:
import numpy as np
c = df.columns.values
c_middle = len(c) // 2
c_last = [c[-1]] * (0 + len(c) % 2)
new_c = np.hstack((c[:c_middle * 2].reshape((2, c_middle), order='F')[::-1].flatten('F'), c_last))When using the (‑1)ⁱ trick on an odd‑column DataFrame, the generated index may exceed the maximum column index; clipping fixes this:
[i + (-1) ** i for i in range(len(df.columns))]import numpy as np
np.clip([i + (-1) ** i for i in range(len(df.columns))], 0, len(df.columns) - 1)Summary
This example demonstrates several straightforward ways to reorder odd and even columns in a pandas DataFrame by leveraging column indices, NumPy array reshaping, and the mathematical property of (‑1)ⁱ. The methods are concise, flexible, and illustrate how to think creatively about data‑frame manipulation.
— Written on May 20, 2022
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
