Fundamentals 5 min read

How to Efficiently Swap Specific Values Between Two Pandas Columns

This tutorial demonstrates two practical methods for conditionally swapping values between two columns in a pandas DataFrame, using boolean masking and NumPy indexing, and explains why direct column swapping may not work as expected.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Efficiently Swap Specific Values Between Two Pandas Columns

Rescuing pandas: Swapping Different Values Between Two Columns

Many developers avoid pandas in favor of other libraries, so this series aims to showcase pandas' power by solving a common data‑manipulation task: exchanging selected values between two columns.

Data Requirement

The goal is to swap the highlighted red and blue regions shown in the figure.

Requirement Breakdown

Swapping entire columns is trivial—just rename them—but swapping only certain values requires extracting one column’s values and filling them with the other column’s values using pandas.

Data Construction

pic2

Requirement Processing

Method One

Create a mask column that marks rows meeting the condition as True, then use boolean indexing to exchange the values.

# map调用函数为自定义条件函数,在这里仅为示例
# 学历列包含数值型,需强转为str再进行自定义条件筛选
mask = df['学历'].astype(str).map(lambda x: '经验不限' in x or '年' in x or x.isdigit())

# 通过布尔提取交换两列数据
df.loc[mask, '经验'], df.loc[mask, '学历'] = df.loc[mask, '学历'], df.loc[mask, '经验']

pic3

Method Two

Leverage NumPy indexing by converting the selected columns to a NumPy array and swapping the columns via slicing.

# mask已在上一步获得
df.loc[mask, ['学历', '经验']] = df.loc[mask, ['学历', '经验']].values[:, [1, 0]]

The swap succeeds as shown below.

ps: Directly swapping two columns with a single assignment does not work.

df.loc[mask, ['经验', '学历']] = df.loc[mask, ['学历', '经验']]

This code runs without effect, likely because the assignment operates on a view rather than a copy.

Summary

Data often requires extraction and reassignment when values are not located in their expected columns. Using pandas’ flexible indexing and assignment capabilities makes such transformations straightforward, saving time for more valuable tasks.

Winter nights are quiet and serene; may you have pleasant dreams.

Created on 2022‑01‑12

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

pandasdata manipulationboolean indexingcolumn swapping
Python Crawling & Data Mining
Written by

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!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.