0

I've been told that my code is correct but I keep getting

ValueError: could not convert string to float: 'Value'"

I'm not sure where I am going wrong.

enter image description here

What can I do to turn data from a CSV file into a float?

Code:

filename = input("Temperature anomaly filename:")
list_temp = []
row = 0
with open(filename) as file:
    for line in file:
        line = line.strip("\n")
        year, temp  = line.split(",")
        if row == 0:
            list_temp.append(float(temp))
        else:
            list_temp.append(float(temp))
        row = row + 1
k = int(input("Enter window size:"))
for index in range(k, len(list_temp)-k):
    year = 1880 + index
    avg = sum(list_temp[index-k:index+k+1]) / (2*k+1)
    print("{}, {:.4f}".format(year, avg))

CSV data

Year,Value
1880,-1.56
1881,-0.08
1882,-0.3
...
2016,0.48
2017,2.63
2018,0.18

Input: 20

imxitiz
  • 3,920
  • 3
  • 9
  • 33

2 Answers2

3

You need to skip the header row. As the error message says, the string "Value" is not a number; it's apparently the title of the temperature column in your csv file (the fact that it's a "ValueError" is just a coincidence). Replace line 12 with continue. Also, you might rather use the csv module for this (read this tutorial).
Try this:

with open(filename) as file:
    for row, line in enumerate(file):
        if row == 0:
            continue
        line = line.strip("\n")
        year, temp  = line.split(",")
        list_temp.append(float(temp))

Edit: See solution from @imxitiz it's a bit cleaner

Noah Wiggin
  • 365
  • 1
  • 6
  • I put in line.strip, that should've skipped the first line, no? – Fora Gamsonly Mar 03 '23 at 05:17
  • that removes the newline character (`\n`) at the end of each line. – Noah Wiggin Mar 03 '23 at 05:19
  • oh man how could i remove that first line? – Fora Gamsonly Mar 03 '23 at 05:22
  • it's handled in `if row == 0: ...` just use `continue` to skip that first iteration (read [here](https://www.w3schools.com/python/ref_keyword_continue.asp) for more info) – Noah Wiggin Mar 03 '23 at 05:25
  • I added that in, however it is still saying the value cannot be turned into float – Fora Gamsonly Mar 03 '23 at 05:29
  • to be clear, I mean you need to *replace* `list_temp.append(float(temp))` (only the one after `if row == 0:`) with `continue`. I tried it with your example input and didn't get that error. If you do get that error, that means there's a non-numeric temperature value in your csv, or a missing comma, or something – Noah Wiggin Mar 03 '23 at 05:33
  • 1
    @Noah Actually, doing `continue` on line 12(Checking if, row==0 is True) would create a flaw, because `row = row + 1` this line is never executed. So, value of `row` will not be change for whole iteration!!! Hence, value of `row` would always be "0" and other condition of `row==0` is never executed. – imxitiz Mar 03 '23 at 05:34
  • 1
    yep good catch, then do `row = row + 1`, then `continue` – Noah Wiggin Mar 03 '23 at 05:36
  • thank you guys so much! now I'm getting no output though haha my expected output is 1900,-0.4171 I think its my "if" loop that's messing it up – Fora Gamsonly Mar 03 '23 at 05:44
  • @Fora Try replacing your for loop with the updated example I added to my answer, using `enumerate` to keep the row count. I did test it – Noah Wiggin Mar 03 '23 at 05:53
  • thank you!if I could like I would! – Fora Gamsonly Mar 03 '23 at 06:32
1

This problem is because of those header row of CSV file as @Noah points out. Here's other solution to solve this problem:

with open(filename) as file:
    next(file)
    for line in file:
        year, temp  = line.split(",")
        list_temp.append(float(temp))

Skipping the first line by doing next(file) would solve that problem. Which is considered better for large file. solve all these problem.

Also, float() function automatically removes any leading or trailing white space characters (such as spaces, tabs, and newlines) before attempting the conversion. So, no need to do, strip(). float() documentation

imxitiz
  • 3,920
  • 3
  • 9
  • 33