【问题标题】:find the rows with specific pattern查找具有特定模式的行
【发布时间】:2023-01-31 21:11:09
【问题描述】:

我需要在数据框中找到条目,其中其中一列具有特定模式,例如 01-02-11-55-00115 换句话说 Number-number-number-number-number

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)df.head()

检索具有该条件的行,条件将在“代码”列中,因此代码必须检索第一行和第二行

【问题讨论】:

    标签: pandas


    【解决方案1】:

    这是一种方法(str.isnumeric) :

    out = df.loc[df["code"].replace("-", "", regex=True).str.isnumeric()]
    

    的 输出 :

    print(out)
                 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
    

    或者,如果您需要标记这些行,请使用:

    df["flag"] = df["code"].replace("-", "", regex=True).str.isnumeric()
    
    print(df)
                   name               code favorite_color  grade   flag
    0    Willard Morris  01-02-11-55-00115           blue     88   True
    1       Al Jennings  01-02-11-55-00445           blue     92   True
    2      Omar Mullins               test         yellow     95  False
    3  Spencer McDaniel  01-0t-11-55-00115          green     70  False
    

    【讨论】:

      【解决方案2】:

      如果是十进制或-,则过滤值:

      df = df[df["code"].str.contains(r'^[0-9-]+$')]
      print (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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-02
        • 1970-01-01
        • 2022-11-02
        • 2023-01-08
        • 2019-11-08
        • 2022-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多