2

I'm trying to find the average of each row in a CSV file as follows:

import csv

with open('file.csv') as handle:
    reader = csv.reader(handle, quoting=csv.QUOTE_NONNUMERIC)
    for row in reader:
        scores = row
        average = sum([float(score) for score in scores]) / len(scores)

However, I'm always getting the following error:

ValueError: could not convert string to float:
'0.3183098861837984\t0.0021994616367169914\t0.0017398716418448568\t0.002779444153298143\t0.0044629274068791434\t0.0012644430669709003\t0.003083531279794444\t0.004509550881264837\t0.003608705125189259\t0.006833702582258458\t0.0018230394455706783\t0.001852023514636493\t0.004720184835956941\t0.006038977572546727\t0.004769535833937563\t0.0016622734203053761\t0.009311664834557762\t0.002327769746299017\t0.0020053588662354263\t0.006252191840044608\t0.006794853486350821\t0.007258945010249113\t0.00559368878955651\t0.002391455287537788\t0.002168369276873031'

How can I fix this error?

4
  • It looks like you're treating multiple tab-delimited values asa single value and trying to convert them all to a single float. Have you tried splitting the row on tab characters before trying to convert? Commented Jul 29, 2019 at 20:25
  • Specify separator. Looks like tab character \t Commented Jul 29, 2019 at 20:25
  • 1
    Does it solve your problem after adding delimiter='\t'? Commented Jul 29, 2019 at 20:32
  • Specifying the field separator is mentioned here in the documentation (and shown in many of the example code snippets). Commented Jul 29, 2019 at 21:38

1 Answer 1

2
  • your .csv file is tab separated and not , separated
  • use delimiter='\t' while reading the csv file. This should fix the problem.
import csv

with open('file.csv') as handle:
    reader = csv.reader(handle, delimiter='\t', quoting=csv.QUOTE_NONNUMERIC)
    for row in reader:
        scores = row
        average = sum([float(score) for score in scores]) / len(scores)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.