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.
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:"泪目"})
dfMethod 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)
dfMethod 3 – Using replace
df['col4'] = df['col1'].replace(1, '开心').replace(2, '悲伤').replace(3, '难过').replace(4, '泪目')
dfMethod 4 – Dictionary Lookup with apply
def get_value(s):
mapping = {1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"}
return mapping[s]
df['col5'] = df['col1'].apply(get_value)
dfMethod 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)
dfMethod 6 – Bulk Replacement with replace
df['col7'] = df['col1'].replace([1, 2, 3, 4], ['开心', '悲伤', '难过', '泪目'])
dfConclusion
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.
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.
