pandas 中的字符串到浮点数的转换错误 [无法将字符串转换为浮点数:'dvic']

string to float convert error in pandas [could not convert string to float: 'dvic']

我正在尝试从标题列中提取年份并将其转换为 'int' 或 'float'。转换时显示错误(标记为黄色)

link -> https://colab.research.google.com/drive/1nGCdvCLUQYqU8zsEF3PaGrng-ay3IkIu?usp=sharing

考虑到 title 列仅包含年份形式的数字。

如果要将名为 year 的新列添加到 df

df['year'] = df.title.str.extract(r"\((\d+)\)")

如果你想 year 作为 list/series

year = df.title.str.extract(r'(\d+)')

输出 在示例的最后一行添加了一个虚拟标题

    movieId title   genres  year
0   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy 1995
1   2   Jumanji (1995)  Adventure|Children|Fantasy  1995
2   3   Grumpier Old Men (1995) Comedy|Romance  1995
3   4   Waiting to Exhale (1995)    Comedy|Drama|Romance    1995
4   5   Father of the Bride Part II (1995)  Comedy  1995
5   6   Dummy 3 Title (1995)    Comedy  1995

您可以拆分最后一个空格,然后去除括号

df[['title', 'year']] = df['title'].str.rsplit(' ', 1, expand=True)
df['year'] = df['year'].str.strip('()').astype(int)
print(df)

       title  year
0  Toy Story  1995
1    Jumanji  1995