如何通过正则表达式过滤 Pandas 中的行?

pythonserver side programmingprogramming更新于 2025/10/28 0:44:17

正则表达式 (regex) 是定义搜索模式的字符序列。要通过正则表达式过滤 Pandas 中的行,我们可以使用 str.match() 方法。

步骤

  • 创建一个二维、大小可变、可能异构的表格数据 df。
  • 打印输入 DataFrame df。
  • 为表达式初始化一个变量 regex。提供一个字符串值作为正则表达式,例如,字符串 'J.*' 将过滤所有以字母 'J' 开头的条目。
  • 使用 df.column_name.str.match(regex) 通过提供的正则表达式过滤给定列名中的所有条目。

示例


import pandas as pd

df = pd.DataFrame(
   dict(
      name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
      marks=[89, 23, 100, 56, 90],
      subjects=["Math", "Physics", "Chemistry", "Biology", "English"]
   )
)

print "Input DataFrame is:\n", df

regex = 'J.*'
print "After applying ", regex, " DataFrame is:\n", df[df.name.str.match(regex)]

regex = 'A.*'
print "After applying ", regex, " DataFrame is:\n", df[df.name.str.match(regex)]

输出

Input DataFrame is:

     name    marks   subjects
0    John     89        Math
1   Jacob     23     Physics
2     Tom    100   Chemistry
3     Tim     56     Biology
4    Ally     90     English

After applying J.* DataFrame is:

    name   marks   subjects
0   John     89        Math
1  Jacob     23     Physics

After applying A.* DataFrame is:

    name   marks   subjects
4   Ally     90     English

相关文章


有用资源