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

如何筛选DataFrame中code列符合指定数字分隔格式的行

在Pandas DataFrame中筛选符合指定格式的行

要筛选出code列符合「数字-数字-数字-数字-数字」格式(即由连字符分隔的五组纯数字)的行,可以借助正则表达式结合Pandas的字符串匹配方法实现。

实现思路

  • 编写匹配目标格式的正则表达式,确保code内容是由连字符分隔的五段纯数字;
  • 利用Pandas的str.match()方法筛选出符合正则规则的行。

完整代码示例

import pandas as pd

raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
            'code': ['01-02-11-55-00115','01-02-11-55-00445','test', '01-0t-11-55-00115'],
            'favorite_color': ['blue', 'blue', 'yellow', "green"],
            'grade': [88, 92, 95, 70]}
df = pd.DataFrame(raw_data)

# 筛选符合格式的行
filtered_df = df[df['code'].str.match(r'^\d+-\d+-\d+-\d+-\d+$')]
print(filtered_df)

输出结果

name               code favorite_color  grade
0  Willard Morris  01-02-11-55-00115            blue     88
1     Al Jennings  01-02-11-55-00445            blue     92

如果需要严格匹配示例中「前四段为两位数字、第五段为任意位数数字」的格式,可将正则表达式调整为r'^\d{2}-\d{2}-\d{2}-\d{2}-\d+$',进一步提升匹配精度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:31:03