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.
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]})
dfMethod 1: map()
Use a dictionary with map to create a new column.
df['col2'] = df['col1'].map({1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"})
dfMethod 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)
dfMethod 3: replace()
Chain replace calls for each value.
df['col4'] = df['col1'].replace(1, '开心').replace(2, '悲伤').replace(3, '难过').replace(4, '泪目')
dfMethod 4: apply() with dictionary lookup
def get_value(s):
dict = {1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"}
return dict[s]
df['col5'] = df['col1'].apply(get_value)
dfMethod 5: map() with custom function
def get_value(s):
dict = {1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"}
return dict[s]
df['col5'] = df['col1'].map(get_value)
dfMethod 6: replace() with list mapping
df['col7'] = df['col1'].replace([1, 2, 3, 4], ['开心', '悲伤', '难过', '泪目'])
dfConclusion
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.
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.
