数据集中有一列“高度”,如下所示。
Height
0 6-2
1 6-6
2 6-5
3 6-5
4 6-10
5 6-9
6 6-8
7 7-0
它的类型是dtype: object
,现在我想把它转换成浮点,即6.2,6.6我尝试了使用替换方法,但是它没有工作。你能告诉我怎么做吗?我是刚认识潘达斯的。
发布于 2019-04-17 13:55:30
使用Series.str.replace
替换子字符串,并通过以下方式将其转换为浮动:
df['Height'] = df['Height'].str.replace('-','.').astype(float)
或者将Series.replace
与regex=True
一起用于替换子字符串:
df['Height'] = df['Height'].replace('-','.', regex=True).astype(float)
发布于 2019-04-17 13:58:33
您可以使用lambda函数映射列以更改它。
df.loc[:,'Height'] = df.loc[:,'Height'].map(lambda x: float(str(x).replace('-','.')))
我不知道你的用例,但如果这是英寸,要小心。
https://stackoverflow.com/questions/55729179
复制相似问题