【问题标题】:how to filter string with regular expression in pandas dataframes如何在熊猫数据框中使用正则表达式过滤字符串
【发布时间】:2018-12-25 12:45:48
【问题描述】:
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13] ['Adam', 14]]
df = pd.DataFrame(data,columns=['Name','Age'])
print(df)

    Name    Age
0   Alex    10
1   Bob     12
2   Clarke  13
3   Adam    14

我只想获取以 A 开头的名称。我尝试了以下代码 mask = df['Name'].str.contains("A*")

 mask
 0    True
 1    True
 2    True
 Name: Name, dtype: bool 

 df = df[mask]

   Name    Age

0    Alex    10
1   Bob      12
2   Clarke   13

但我想得到结果 姓名年龄

0    Alex    10

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用这个:

    mask = df['Name'].str.startswith("A")
    

    例如:

    In [52]: df
    Out[52]: 
         Name  Age
    0    Alex   10
    1     Bob   12
    2  Clarke   13
    3    Adam   14
    
    In [53]: mask = df['Name'].str.startswith("A")
    
    In [54]: df[mask]
    Out[54]: 
       Name  Age
    0  Alex   10
    3  Adam   14
    

    对于正则表达式匹配,正如@swiftg 所建议的:

    mask = df['Name'].str.match("^A.*")
    

    【讨论】:

    • 另外,我想检查像 A, * 这样的正则表达式,如何处理这种情况
    • mask = df['Name'].str.match("^A.*") 用于正则表达式匹配。
    • @TECHI,​​ * 匹配是“glob”匹配,不同于正则表达式。 Please look it up.
    • 那么如何处理只输入*呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2017-06-18
    • 2018-09-24
    • 2021-08-09
    • 2019-07-18
    • 2020-10-23
    • 2016-01-15
    相关资源
    最近更新 更多