如何在DataFrame列中筛选保留6位数字,其余标记为‘无效’
Clean Pandas DataFrame Post Code to Keep Only 6-Digit Values
Hey there! Let's sort out this post code cleaning task for your DataFrame. The goal is to retain only entries that are exactly 6 digits, and mark everything else as Nil (swap to 'Not Valid' if you prefer—just adjust the string in the code). Here are two straightforward ways to get your desired output:
Method 1: Using numpy.where with Regex Matching
This approach checks each value against a strict regex pattern and replaces non-matching entries in one clean line:
import pandas as pd import numpy as np # Create the cleaned post code column data['Cleaned_Post_Code'] = np.where( # Convert all values to strings first, then check for exactly 6 digits data['Post_Code'].astype(str).str.match(r'^\d{6}$'), # Keep the original value if it matches the pattern data['Post_Code'], # Mark non-matching values as 'Nil' 'Nil' )
Breakdown of how this works:
astype(str)ensures numeric values (like8or4) are treated as strings, so length checks work correctly.- The regex
r'^\d{6}$'enforces strict rules:^= start of the string,$= end of the string\d{6}= exactly 6 numeric digits
This rejects any value with extra characters, wrong length, or non-numeric content.
np.whereacts as a conditional switch: keep the original value if it matches, else useNil.
Method 2: Pandas-Native str.extract with fillna
If you prefer avoiding numpy, this pandas-only approach works equally well:
import pandas as pd # Extract valid 6-digit values, fill invalid entries with 'Nil' data['Cleaned_Post_Code'] = ( data['Post_Code'] .astype(str) .str.extract(r'^(\d{6})$', expand=False) .fillna('Nil') )
Breakdown of how this works:
str.extract(r'^(\d{6})$')pulls out the 6-digit pattern if it exists; non-matching values returnNaN.fillna('Nil')replaces allNaNentries with your desired invalid marker.
Testing with Your Sample Data
Both methods will produce exactly the output you expect:
- Valid 6-digit values like
629785,460803are retained. - Values like
760-\63,S4P2Z6,999999999, or single-digit numbers get marked asNil.
内容的提问来源于stack exchange,提问作者Rahul rajan
相关产品推荐
相关产品推荐

