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

如何在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 (like 8 or 4) 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.where acts as a conditional switch: keep the original value if it matches, else use Nil.

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 return NaN.
  • fillna('Nil') replaces all NaN entries 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, 460803 are retained.
  • Values like 760-\63, S4P2Z6, 999999999, or single-digit numbers get marked as Nil.

内容的提问来源于stack exchange,提问作者Rahul rajan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:33:21