Swap Odd and Even Columns in a Pandas DataFrame – 3 Simple Python Methods
This article demonstrates three Python approaches to exchange odd‑indexed and even‑indexed columns in a Pandas DataFrame, providing complete code snippets, execution results, and a concise explanation for each method.
Introduction
In a recent Python community challenge, participants were asked to write code that swaps the positions of odd‑numbered and even‑numbered columns in a Pandas DataFrame (e.g., turning column A, B into B, A).
Method One
A contributor named kiddo offered a solution with full code and output screenshots.
Method Two
Another participant, 月神 , simplified the solution to a single line that reorders the columns using a list comprehension.
df = df[[df.columns[index + (-1) ** index] for index in range(len(df.columns))]]Method Three
A third approach combines NumPy with Pandas to achieve the same column swap in a compact form.
import numpy as
import pandas as
en = 'abcdef'
df = pd.DataFrame([[i + j for j in list(en)] for i in list(en)], columns=list(en.upper()), index=list(en.upper()))
print('源数据')
print(df)
# swap columns
df = df[np.array((df.columns[1::2], df.columns[::2])).flatten('F')]
print('转换后')
print(df)Conclusion
The article summarizes the three practical methods for swapping odd and even columns in a Pandas DataFrame, encouraging readers to experiment and share alternative solutions.
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.
