python - 将列从对象转换为浮点的问题
问题描述
抓取网站后,我有一个列价格。
5 € 9.500,00
7 € 2.950,00
8 € 5.750,00
11 € 64.718,00
14 € 4.800,00
...
3050 € 8.099,00
3051 € 12.500,00
3052 € 16.900,00
3054 € 699,00
3059 € 6.500,00
dtype: object
我试图删除欧元符号并将其转换为具有标准str.replace.astype(float)
功能的浮点数,但它产生了错误。
我在这里找到了另一种可能性:
locale.setlocale(locale.LC_ALL,'')
df3['Price']=df3.Price.map(lambda x: locale.atof(x.strip('€')))
但是,我现在有一个问题,现在点和价格现在被错误地反映以供我进一步分析:
5 9.500
7 2.950
8 5.750
11 64.718
14 4.800
...
3050 8.099
3051 12.500
3052 16.900
3054 69900.000
3059 6.500
dtype: float64
解决方案
检查您加载数据的方式是否支持thousands
anddecimal
选项,例如 Pandas read_csv
。您也可以设置适当的语言环境,de_DE
例如,但我个人不喜欢弄乱语言环境,因为它们是全局状态。
我个人会用一个简单的字符串替换来解决这个问题:
df3['Price'] = df3.Price.map(lambda x: float(x.strip('€')
.replace('.', '')
.replace(',', '.')))
推荐阅读
- maven - 如何在我的 maven Surefire Reports 中为我的应用程序设置 url?
- node.js - 如何使用节点处理 unix 路径(\)?
- apache-spark - 设置 pyspark 环境时出错
- python - 手动渲染字段---Django
- django - Django:注释相关字段列表
- volttron - 执行代理时发生“连接关闭”
- android - android studio 只启动虚拟机
- android - “无法回滚 - 没有事务处于活动状态(代码 1)”在 API 23 设备上使用 Android Room 库时
- flutter - 使之颤动时面临的问题
- javascript - 使用 google 表格作为数据库从代码进行身份验证