gpt4 book ai didi

python - 将正则表达式应用于 Pandas 数据框

转载 作者:太空狗 更新时间:2023-10-29 16:55:16 24 4
gpt4 key购买 nike

我在将正则表达式函数应用于 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 的列,其中包含连字符之前的年份。我确信没有正则表达式也有更简单的方法,但更重要的是,我想弄清楚我做错了什么

提前感谢您的帮助。

最佳答案

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

关于python - 将正则表达式应用于 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25292838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com