如何将DataFrame的ZIP_CODE列约束为前5位数字并替换原列
Hey there, since you're crunched for time and need a quick fix for those over-length ZIP codes—here's a no-fuss pandas solution that'll extract the first 5 digits and update your DataFrame in one go:
Step-by-Step Solution
First, make sure your ZIP_CODE column is treated as a string (critical if some entries are stored as integers, which would drop leading zeros if we didn't convert them):
import pandas as pd # Convert ZIP_CODE to string type to handle all entry formats df['ZIP_CODE'] = df['ZIP_CODE'].astype(str)
Next, extract the first 5 characters and overwrite the original column. This works perfectly for both valid 5-digit codes (they stay unchanged) and the long entries you mentioned:
# Grab the first 5 characters for every entry df['ZIP_CODE'] = df['ZIP_CODE'].str[:5]
Handling Edge Cases (Optional)
If your DataFrame has NaN values in the ZIP_CODE column, converting to string would turn them into the literal string 'nan'. To keep them as actual NaN values instead, use this adjusted code:
# Preserve NaN values while trimming long ZIP codes df['ZIP_CODE'] = df['ZIP_CODE'].apply(lambda x: x[:5] if pd.notna(x) else x)
That's it—this should get your ZIP_CODE column cleaned up in seconds, so you can move on to the rest of your work!
内容的提问来源于stack exchange,提问作者Jason Deutsch

