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

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

步骤

  • 创建二维、大小可变、潜在异构的表格数据df

  • 打印输入数据帧df

  • 为表达式初始化一个变量正则表达式。提供一个字符串值作为正则表达式,例如,字符串'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 "申请后 ", regex, " DataFrame is:\n", df[df.name.str.match(regex)]

regex = 'A.*'
print "申请后 ", 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

申请后 J.* DataFrame is:

    name   marks   subjects
0   John     89        Math
1  Jacob     23     Physics

申请后 A.* DataFrame is:

    name   marks   subjects
4   Ally     90     English