问题 将正则表达式应用于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  

我认为我很好地掌握了将函数应用于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

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

在此先感谢您的帮助。


11958
2017-08-13 17:46


起源



答案:


当我尝试(一种变体)你的代码时,我得到了 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

13
2017-08-13 18:01



意识到我问的问题是错的,并且得到了你给我的东西。我的错误即将发生b / c我在数据帧的下一年有NaN值。我通过尝试df [“Season”]找到了它.str.split(“ - ”)。str [0] .astype(int)。不管怎样,谢谢,真的很感激 - itjcms18


答案:


当我尝试(一种变体)你的代码时,我得到了 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

13
2017-08-13 18:01



意识到我问的问题是错的,并且得到了你给我的东西。我的错误即将发生b / c我在数据帧的下一年有NaN值。我通过尝试df [“Season”]找到了它.str.split(“ - ”)。str [0] .astype(int)。不管怎样,谢谢,真的很感激 - itjcms18


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

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

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

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


0
2018-04-26 13:01