I am working on a simple data science project with Python. However, I am getting an error which is the following:
ValueError: could not convert string to float:
Here is what my code looks like:
import matplotlib.pyplot as plt
import csv
from datetime import datetime
filename = 'USAID.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
monies = []
for row in reader:
money = int(row[1])
monies.append(money)
print(monies)
if I change the line:
money = int(row[1]) to money = float(row[1])
I get this error: ValueError: could not convert string to float: Here are my tracebacks: first error:
Traceback (most recent call last):
File "funding.py", line 60, in <module>
money = int(row[1])
ValueError: invalid literal for int() with base 10: '42152129.0'
Second Error:
Traceback (most recent call last):
File "funding.py", line 60, in <module>
money = float(row[1])
ValueError: could not convert string to float:
Any help would be great! Thank you!
The first failure is because you passed a string with .
in it to int()
; you can't convert that to an integer because there is a decimal portion.
The second failure is due to a different row[1]
string value; one that is empty.
You could test for that:
if row[1]:
money = float(row[1])
Since you are working with a Data Science project you may want to consider using the pandas
project to load your CSV instead with DataFrame.read_csv()
.
Some of the entries in row[1]
are empty so you probably want to check for those before trying to cast . Pass a default value of, say 0
, if the entry is blank.
Then you should consider using decimal
for computations that relate to money.
I had the same issue while I was learning data visualization using Seaborn. Thanks EdChum 's help, I was able to solve the issue with his approach:
df['col'] = pd.to_numeric(df['col'], errors='coerce')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.