首页 > 解决方案 > 将列从对象转换为浮点的问题

问题描述

抓取网站后,我有一个列价格。

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

标签: pythonpandas

解决方案


检查您加载数据的方式是否支持thousandsanddecimal选项,例如 Pandas read_csv。您也可以设置适当的语言环境,de_DE例如,但我个人不喜欢弄乱语言环境,因为它们是全局状态。

我个人会用一个简单的字符串替换来解决这个问题:

df3['Price'] = df3.Price.map(lambda x: float(x.strip('€')
                                              .replace('.', '')
                                              .replace(',', '.')))

推荐阅读