Reputation: 105
I am working on a program that takes a column from a csv file and averages the sales data, but I am getting an error: "unsupported operand type(s) for +: 'int' and 'str'"
I changed the column in the csv file to numbers and I still get the error.
from csv import reader
opened_file = open('Catalog.csv')
read_file = reader(opened_file)
catalog_data = list(read_file)
sales_data = []
for stuff in catalog_data:
price = stuff[11]
manufacturer = stuff[7]
if manufacturer == 'HASBRO':
sales_data.append(price)
avg_sales = sum(sales_data) / len(sales_data)
Upvotes: -1
Views: 37
Reputation: 105
The int function appened doesn't work:
from csv import reader
opened_file = open('Catalog.csv')
read_file = reader(opened_file)
catalog_data = list(read_file)
sales_data = []
for sales in catalog_data:
price = int(sales[11])
manufacturer = sales[7]
if manufacturer == 'HASBRO':
sales_data.append(int(price))
avg_sales = sum(sales_data) / len(sales_data)
Upvotes: 0
Reputation:
When you're reading in from a CSV file, all the values are strings.
price = stuff[11]
At this point, price
is a string. So when you go:
sales_data.append(price)`
sales_data
is being populated with a list of strings.
When you eventually call sum(sales_data)
, the sum
function fails because it's assuming that sales_data
is populated with numeric values.
To remedy this, simply cast the price data to an appropriate value, like so:
price = float(stuff[11])
Note that if float
ing point values can lose precision, so it's generally not recommended to use float values to store currency values. If precision is important, consider using the decimal module.
Upvotes: 1
Reputation: 32003
use casting like below for price
price = float(stuff[11])
Upvotes: 2