Fundamentals 5 min read

6 Efficient Ways to Replace Categorical Values in Pandas DataFrames

This article walks through six practical Pandas techniques—using map, apply, replace, and dictionary look‑ups—to batch‑replace numeric codes with descriptive strings, complete with code snippets and visual results for each method.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
6 Efficient Ways to Replace Categorical Values in Pandas DataFrames

Introduction

Hello, I’m a Python enthusiast. A follower asked how to batch‑replace numeric codes (1,2,3,4) in a column with corresponding Chinese words ("开心", "悲伤", "难过", "泪目"). Below are several Pandas solutions.

Solution Overview

The idea is straightforward: use Pandas’ mapping and replacement functions. The original data is created as follows:

df = pd.DataFrame({'col1': [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]})
df

Method 1: map()

Use a dictionary with map to create a new column.

df['col2'] = df['col1'].map({1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"})
df

Method 2: apply() with custom function

Define a function that returns the appropriate string and apply it.

def getValue(s):
    if s==1:
        return '开心'
    elif s==2:
        return '悲伤'
    elif s==3:
        return '难过'
    elif s==4:
        return '泪目'

df['col3'] = df['col1'].apply(getValue)
df

Method 3: replace()

Chain replace calls for each value.

df['col4'] = df['col1'].replace(1, '开心').replace(2, '悲伤').replace(3, '难过').replace(4, '泪目')
df

Method 4: apply() with dictionary lookup

def get_value(s):
    dict = {1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"}
    return dict[s]

df['col5'] = df['col1'].apply(get_value)
df

Method 5: map() with custom function

def get_value(s):
    dict = {1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"}
    return dict[s]

df['col5'] = df['col1'].map(get_value)
df

Method 6: replace() with list mapping

df['col7'] = df['col1'].replace([1, 2, 3, 4], ['开心', '悲伤', '难过', '泪目'])
df

Conclusion

The six approaches—using map, apply, replace, and dictionary look‑ups—demonstrate how to efficiently replace numeric codes with meaningful strings in a Pandas DataFrame, providing flexible options for different coding styles.

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.

PythonMAPdataframepandasapplyreplacevalue replacement
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.