我在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的列,其中包含连字符之前的年份。我敢肯定,如果没有正则表达式,这是一种更简单的方法,但更重要的是,我想弄清楚我做错了什么
在此先感谢您的帮助。
当我尝试(一种变体)你的代码时,我得到了 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
当我尝试(一种变体)你的代码时,我得到了 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
通过编写以下代码可以解决问题:
import re
def split_it(year):
x = re.findall('([\d]{4})', year)
if x :
return(x.group())
df['Season2'] = df['Season'].apply(split_it)
你遇到了这个问题,因为有些行在字符串中没有年份