Swap Odd and Even Columns in a Pandas DataFrame – 3 Quick Methods
This article demonstrates three different Python approaches to exchange the positions of odd‑numbered and even‑numbered columns in a pandas DataFrame, providing complete code examples, step‑by‑step explanations, and visual results to help readers master column reordering.
1. Introduction
The task is to swap the odd‑numbered columns with the even‑numbered columns in a pandas DataFrame, e.g., turning columns A, B into B, A.
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)
# Please complete the code
print('转换后')
print(df)Original data:
Result after swapping:
2. Implementation
Method 1
Kiddo’s solution swaps columns using direct indexing. The code and its output are shown below.
Method 2
MoonGod simplified the approach to a one‑liner that reorders columns based on their index.
df = df[[df.columns[index + (-1) ** index] for index in range(len(df.columns))]]Result:
Method 3
MoonGod provided another concise solution using NumPy to flatten a reordered column list.
import numpy as np
import pandas as pd
# Data is prepared above; complete the remaining code to achieve the swap.
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)
# Please complete the code
df = df[np.array((df.columns[1::2], df.columns[::2])).flatten('F')]
print('转换后')
print(df)Result:
3. Summary
The article presented three practical Python methods to interchange odd and even columns in a pandas DataFrame, each with full code and visual verification, enabling readers to choose the approach that best fits their workflow.
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.
