【问题标题】:applying regex to a pandas dataframe将正则表达式应用于熊猫数据框
【发布时间】:2014-10-07 04:58:02
【问题描述】:

我在将正则表达式函数应用于 python 数据框中的列时遇到问题。这是我的数据框的头部:

               Name   Season          School   G    MP  FGA  3P  3PA    3P%
 74       Joe Dumars  1982-83   McNeese State  29   NaN  487   5    8  0.625   
 84      Sam Vincent  1982-83  Michigan State  30  1066  401   5   11  0.455   
 176  Gerald Wilkins  1982-83     Chattanooga  30   820  350   0    2  0.000   
 177  Gerald Wilkins  1983-84     Chattanooga  23   737  297   3   10  0.300   
 243    Delaney Rudd  1982-83     Wake Forest  32  1004  324  13   29  0.448  

我认为我已经很好地掌握了将函数应用于 Dataframes 的能力,所以我的 Regex 技能可能有所欠缺。

这是我整理的:

import re

def split_it(year):
    return re.findall('(\d\d\d\d)', year)

 df['Season2'] = df['Season'].apply(split_it(x))

TypeError: expected string or buffer

输出将是一个名为 Season2 的列,其中包含连字符之前的年份。我确信没有正则表达式有一种更简单的方法,但更重要的是,我试图找出我做错了什么

提前感谢您的帮助。

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    我会提取:

    df['Season2']=df['Season'].str.extract(r'(\d{4}))
    

    【讨论】:

      【解决方案2】:

      你也可以使用 pandas 的原生函数来做到这一点。

      检查 this page 以获取接受正则表达式的 pandas 函数。对于您的情况,您可以这样做

      df["Season"].str.extract(r'([\d]{4}))')
      

      【讨论】:

        【解决方案3】:

        您可以简单地使用str.extract

        df['Season2']=df['Season'].str.extract(r'(\d{4})-\d{2}')
        

        您可以在此处找到 \d{4}-\d{2}(例如 1982-83),但仅提取括号 \d{4} 之间的捕获组(例如 1982)

        【讨论】:

          【解决方案4】:

          我遇到了完全相同的问题。感谢@DSM 的回答。 仅供参考@itjcms,您可以通过删除'\d\d\d\d' 的重复来改进功能。

          def split_it(year):  
              return re.findall('(\d\d\d\d)', year)
          

          变成:

          def split_it(year):
              return re.findall('(\d{4})', year)
          

          【讨论】:

            【解决方案5】:

            可以通过编写以下代码来解决所提问题:

            import re
            def split_it(year):
                x = re.findall('([\d]{4})', year)
                if x :
                  return(x.group())
            
            df['Season2'] = df['Season'].apply(split_it)
            

            您遇到了这个问题,因为有些行在字符串中没有年份

            【讨论】:

              【解决方案6】:

              当我尝试(变体)您的代码时,我得到NameError: name 'x' is not defined-- 但事实并非如此。

              你可以使用任何一个

              df['Season2'] = df['Season'].apply(split_it)
              

              df['Season2'] = df['Season'].apply(lambda x: split_it(x))
              

              但第二种方法只是编写第一种方法的一种更长且更慢的方法,因此没有多大意义(除非您有其他要处理的参数,我们不在这里。)您的函数将返回一个 列表,但是:

              >>> df["Season"].apply(split_it)
              74     [1982]
              84     [1982]
              176    [1982]
              177    [1983]
              243    [1982]
              Name: Season, dtype: object
              

              虽然你可以很容易地改变它。 FWIW,我会使用矢量化字符串操作并做类似的事情

              >>> df["Season"].str[:4].astype(int)
              74     1982
              84     1982
              176    1982
              177    1983
              243    1982
              Name: Season, dtype: int64
              

              >>> df["Season"].str.split("-").str[0].astype(int)
              74     1982
              84     1982
              176    1982
              177    1983
              243    1982
              Name: Season, dtype: int64
              

              【讨论】:

              • 意识到我问错了问题并且得到了你给我的东西。我的错误来了 b/c 我在数据框的下一年有 NaN 值。我通过尝试 df["Season"].str.split("-").str[0].astype(int) 发现了这一点。不过还是谢谢,真的很感激
              猜你喜欢
              • 1970-01-01
              • 2018-02-17
              • 2020-10-23
              • 2021-03-13
              • 1970-01-01
              • 1970-01-01
              • 2018-02-22
              • 1970-01-01
              • 2021-08-09
              相关资源
              最近更新 更多