如何用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
相关产品推荐
相关产品推荐

