Hendrra
Hendrra

Reputation: 859

An error while converting string into float in a CSV file

I have created a CSV (Comma delimited) file from an Excel file. I would like to analyze them in Python (ver. 3.5) using Spyder.

I managed to create nice lists from the CSV file I've mentioned above. 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: 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 file

I would really appreciate any help or tips.

Upvotes: 0

Views: 196

Answers (1)

Rakesh
Rakesh

Reputation: 82755

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

Upvotes: 1

Related Questions