Fundamentals 5 min read

6 Powerful Pandas Tricks to Replace Categorical Codes with Text

This article walks through six different Pandas techniques—including map, apply, replace, and dictionary mapping—to batch‑replace numeric codes (1‑4) with descriptive Chinese strings such as “开心” and “悲伤”, providing clear code snippets and visual results for each method.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
6 Powerful Pandas Tricks to Replace Categorical Codes with Text

Introduction

In response to a fan’s question about converting a column of numeric codes (1, 2, 3, 4) into corresponding Chinese words, this article presents six Pandas solutions.

Method 1 – Mapping with a Dictionary

Using map to replace values:

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

Method 2 – Custom Function with apply

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 – Using replace

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

Method 4 – Dictionary Lookup with apply

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

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

Method 5 – Mapping with a Function and map

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

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

Method 6 – Bulk Replacement with replace

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

Conclusion

The six approaches demonstrate how to efficiently replace numeric codes with descriptive strings in a Pandas DataFrame, giving readers multiple options to choose from based on their coding style and performance needs.

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.

MAPapplyreplace
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.