6 Powerful Pandas Tricks to Replace Numeric Codes with Text
This article walks through six different Pandas techniques for converting numeric codes (1‑4) into descriptive strings such as "happy" or "sad", providing clear code examples, visual results, and practical tips for efficient batch replacement in dataframes.
Preface
Hello, I am a Python enthusiast. Recently a fan asked how to replace a column of numeric codes (1, 2, 3, 4) with corresponding text values in Pandas, so I am sharing several solutions.
Solution Process
The data frame is created with the following code:
df = pd.DataFrame({'col1': [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]})
dfMethod 1: Mapping with a Dictionary
Use map to assign new values:
df['col2'] = df['col1'].map({1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"})
dfResult:
Method 2: Custom Function with apply
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)
dfResult:
Method 3: Using replace Directly
Chain replace calls for each value:
df['col4'] = df['col1'].replace(1, '开心').replace(2, '悲伤').replace(3, '难过').replace(4, '泪目')
dfResult:
Method 4: Mapping via apply with a Dictionary
def get_value(s):
dict = {1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"}
return dict[s]
df['col5'] = df['col1'].apply(get_value)
dfResult:
Method 5: Mapping with map and a Helper Function
def get_value(s):
dict = {1:"开心", 2:"悲伤", 3:"难过", 4:"泪目"}
return dict[s]
df['col5'] = df['col1'].map(get_value)
dfResult:
Method 6: Vectorized replace with Lists
df['col7'] = df['col1'].replace([1, 2, 3, 4], ['开心', '悲伤', '难过', '泪目'])
dfResult:
Conclusion
This article collected six Pandas approaches—mapping, apply, replace, and map —to batch‑replace numeric codes with meaningful strings, providing code snippets and visual output to help readers solve the problem efficiently.
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.
