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

如何用Python Pandas过滤DataFrame,移除指定IP段的行?

移除DataFrame中匹配特定IP段的行

直接用Pandas的字符串匹配功能结合正则表达式就能解决,操作步骤如下:

  • 先确认你的IP列(假设列名为ip_address)是字符串类型,若不是先转换:df['ip_address'] = df['ip_address'].astype(str)
  • 用正则表达式^10\.\d+\.(220|240)\.\d+$精准匹配10.x.220.x或10.x.240.x格式的IP
  • 通过取反符号~筛选出不匹配该模式的行,得到过滤后的数据集

示例代码:

# 转换IP列为字符串类型(若需要)
df['ip_address'] = df['ip_address'].astype(str)

# 过滤目标IP行
filtered_df = df[~df['ip_address'].str.match(r'^10\.\d+\.(220|240)\.\d+$')]

如果需要更严格的IP合法性校验(比如每个网段数值不超过255),可以用更精确的正则:

strict_ip_pattern = r'^10\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(220|240)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$'
filtered_df = df[~df['ip_address'].str.match(strict_ip_pattern)]

处理完成后,filtered_df就是移除了目标IP行后的DataFrame,可直接用于后续分析。

内容的提问来源于stack exchange,提问作者Dennis Nielsen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:26:27