You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataFrame的ZIP_CODE列约束为前5位数字并替换原列

Fixing Long ZIP Codes in Your DataFrame

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:23:44