当我尝试(一种变体)您的代码时,我得到了
NameError: name 'x' is not defined-事实并非如此。
您可以使用
df['Season2'] = df['Season'].apply(split_it)
要么
df['Season2'] = df['Season'].apply(lambda x: split_it(x))
但是第二个只是编写第一个的一种较长且较慢的方式,因此没有太多意义(除非您要处理其他参数,我们不在这里。)尽管如此,您的函数将返回一个 list :
>>> 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 198284 1982176 1982177 1983243 1982Name: Season, dtype: int64
要么
>>> df["Season"].str.split("-").str[0].astype(int)74 198284 1982176 1982177 1983243 1982Name: Season, dtype: int64


