简体   繁体   English

将字符串转换为CSV文件中的float时出错

[英]An error while converting string into float in a CSV file

I have created a CSV (Comma delimited) file from an Excel file. 我已经从Excel文件创建了CSV(逗号分隔)文件。 I would like to analyze them in Python (ver. 3.5) using Spyder. 我想使用Spyder在Python(3.5版)中对其进行分析。

I managed to create nice lists from the CSV file I've mentioned above. 我设法从上面提到的CSV文件创建了不错的列表。 My next goal is to convert the strings into floats so that I would be able to do some calculations using them. 我的下一个目标是将字符串转换为浮点数,以便能够使用它们进行一些计算。 However an error occurred and I have no idea how can I deal with it. 但是发生了错误,我不知道该如何处理。

This is the error message: 这是错误消息: 错误信息

Here's my code: 这是我的代码:

import pandas
colnames = ['GDP', 'Unemployment', 'CPI', 'HousePricing']
data = pandas.read_csv('C:/PATH.csv', 
                       names = colnames, header=None, sep=';')
GDP = data.GDP.tolist()
data['GDP'] = data['GDP'].astype(float)
print(GDP)

That's how my CSV file looks like: 这就是我的CSV文件的样子: CSV文件

I would really appreciate any help or tips. 我将不胜感激任何帮助或提示。

Use 采用

data['GDP'] = data['GDP'].str.replace(",", ".").astype(float)

You are getting the error because of comma. 由于逗号导致出现错误。 Replacing it with dot should fix your issue. 用点代替它可以解决您的问题。

Demo: 演示:

import pandas as pd
df = pd.DataFrame({'GDP': ["1,21", "2.2", "3,4", "5,66", "77,09"]})
print df['GDP'].str.replace(",", ".").astype(float)

Output: 输出:

0     1.21
1     2.20
2     3.40
3     5.66
4    77.09
Name: GDP, dtype: float64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM