在 Pandas 系列中拆分字符串和整数 - Python

Split string and integer in Pandas series - Python

我在 Pandas 数据框中有一列,“电影标题”和“年份”(例如“玩具总动员 (1995)”)都在同一个字符串中。 我必须将它们分成 2 个不同的列,当然年份必须是整数。 我尝试使用这种方法(如下),但年份仍然是“object”类型,因为它有括号。 另外,它不适用于一部电影(还有一个标题)...

split_movie = movies["Movie"].str.rsplit(" ", n = 1, expand=True)
movies["Movie Title"] = split_movie[0]
movies["Movie Year"] = split_movie[1]

我不知道我是否可以使用 pd.year 方法,或者我是否必须通过创建列表来拆分 Python 中的字符串...

感谢您的帮助!

使用str.extractall:

>>> df.join(df['Movie'].str.extractall(r'\s*(.*\S)\s*\((\d{4})\)') \
                       .rename(columns={0: 'Movie Title', 1: 'Movie Year'}) \
                       .reset_index(drop=True))

              Movie Movie Title Movie Year
0  Toy Story (1995)   Toy Story       1995

@Bill 增强了正则表达式。

更接近您的原始代码...

尝试:

movies[['Title', 'Year']] = movies["Movie"].str.rsplit("(", n=1, expand=True)
movies['Year'] = movies['Year'].str.replace(')', '', regex=False)
movies['Year'] = movies['Year'].astype('int64')
print(movies.info())

输出:

 #   Column   Non-Null Count  Dtype 
---  ------   --------------  ----- 
 0   Movie    15 non-null     object 
 1   Title    15 non-null     object
 2   Year     15 non-null     int64