How to Efficiently Swap Specific Values Between Two Pandas Columns
This tutorial shows how to exchange selected values between two columns in a pandas DataFrame using boolean masking and NumPy indexing, providing two practical methods with complete code examples and explanations.
Data Requirement
This article demonstrates a simple data manipulation task: swapping the values in the red‑boxed region with those in the blue‑boxed region of a DataFrame.
Requirement Breakdown
Swapping entire columns is trivial—just rename them. Here we need to exchange only part of the data, so we create a mask, extract the target rows, and fill each column with the other's values using pandas.
Constructing the Data
Processing the Requirement
Method One
Create a mask column that marks rows meeting the condition, then use boolean indexing to swap the values.
# map calls a custom condition function (example only)
# The "学历" column contains numeric values, so cast to str for filtering
mask = df['学历'].astype(str).map(lambda x: '经验不限' in x or '年' in x or x.isdigit())
# Swap the two columns where the mask is True
df.loc[mask, '经验'], df.loc[mask, '学历'] = df.loc[mask, '学历'], df.loc[mask, '经验']Method Two
Use NumPy to swap the columns by accessing the underlying array values.
# mask obtained in the previous step
df.loc[mask, ['学历', '经验']] = df.loc[mask, ['学历', '经验']].values[:, [1, 0]]The swap succeeds as shown below.
Note: Directly assigning one column to another (e.g.,
df.loc[mask, ['经验', '学历']] = df.loc[mask, ['学历', '经验']]) does not perform the swap because pandas creates a view that cannot be overwritten in place.
Summary
When data does not reside in the expected columns, extracting and reassigning values is necessary. Pandas provides powerful data manipulation capabilities that make such column‑level swaps straightforward, allowing you to focus on more meaningful analysis tasks.
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.
