首页 > 解决方案 > 熊猫中的字符串到浮点转换错误[无法将字符串转换为浮点:'dvic']

问题描述

在此处输入图像描述

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

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

标签: pythonpandasstringdataframeseries

解决方案


考虑title列仅由年份形式的数字组成。

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

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

如果你想year作为一个列表/系列

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

推荐阅读