将正则表达式应用于pandas数据帧

itj*_*s18 18 python regex pandas

我在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  
Run Code Online (Sandbox Code Playgroud)

我认为我已经很好地掌握了将函数应用于Dataframes,所以也许我的正则表达式技能缺乏.

这是我放在一起的东西:

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
Run Code Online (Sandbox Code Playgroud)

输出将是一个名为Season2的列,其中包含连字符之前的年份.我敢肯定,如果没有正则表达式,这是一种更简单的方法,但更重要的是,我想弄清楚我做错了什么

在此先感谢您的帮助.

DSM*_*DSM 21

当我尝试(一种变体)我得到的代码NameError: name 'x' is not defined- 它不是.

你也可以使用

df['Season2'] = df['Season'].apply(split_it)
Run Code Online (Sandbox Code Playgroud)

要么

df['Season2'] = df['Season'].apply(lambda x: split_it(x))
Run Code Online (Sandbox Code Playgroud)

但是第二个只是编写第一个的更慢更慢的方式,所以没有多大意义(除非你有其他参数要处理,我们不在这里.)你的函数将返回一个列表,但是:

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

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

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

要么

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

  • 意识到我问错了问题并且得到了你给我的东西。我的错误即将到来 b/ci 在数据框下方的年份中具有 NaN 值。我通过尝试 df["Season"].str.split("-").str[0].astype(int) 发现了这一点。无论如何,谢谢,真的很感激 (2认同)

Gab*_*iel 15

你可以简单地使用 str.extract

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

在这里您找到\d{4}-\d{2}(例如 1982-83)但只提取括号之间的捕获组\d{4}(例如 1982)


小智 8

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

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

df['Season2'] = df['Season'].apply(split_it)
Run Code Online (Sandbox Code Playgroud)

You were facing this problem as some rows didn't had year in the string