Error: could not convert string to float in Python

Advertisements

I am trying to read two columns of data, Mean and Std from the file Mean.Std.txt. But I am running into an error which I have shown below. I also present the expected output.

import numpy as np

Mean,Std = np.loadtxt('Mean_Std.txt',unpack=True)
print([Mean])
print([Std])

The data in Mean_Std.txt looks like

Mean              Std
41.96969696969697 0.22727272727273018
29.646464646464647 2.3263867473915276
24.444444444444443 2.836612913158948
22.424242424242426 3.2698851295313993
21.262626262626263 3.4897856988730362
20.80808080808081 4.038667556139951
20.606060606060606 4.342039357850636
20.606060606060606 4.342039357850636
20.606060606060606 4.342039357850636
20.606060606060606 4.342039357850636

The error is

Traceback (most recent call last):

  File "C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept17_2022\220\var_1_beta_1e-1\Test.py", line 19, in <module>
    Mean,Std = np.loadtxt('Mean_Std.txt',unpack=True)

  File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1146, in loadtxt
    for x in read_data(_loadtxt_chunksize):

  File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\npyio.py", line 997, in read_data
    items = [conv(val) for (conv, val) in zip(converters, vals)]

  File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\npyio.py", line 997, in <listcomp>
    items = [conv(val) for (conv, val) in zip(converters, vals)]

  File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\npyio.py", line 734, in floatconv
    return float(x)

ValueError: could not convert string to float: 'Mean'

The expected output is

[array([41.96969697, 29.64646465, 24.44444444, 22.42424242, 21.26262626,
       20.80808081, 20.60606061, 20.60606061, 20.60606061, 20.60606061])]
[array([0.22727273, 2.32638675, 2.83661291, 3.26988513, 3.4897857 ,
       4.03866756, 4.34203936, 4.34203936, 4.34203936, 4.34203936])]

>Solution :

Use skiprows=1 to skip header row

Mean,Std = np.loadtxt('Mean_Std.txt',unpack=True, skiprows=1)
print([Mean])
print([Std])
[array([41.96969697, 29.64646465, 24.44444444, 22.42424242, 21.26262626,
       20.80808081, 20.60606061, 20.60606061, 20.60606061, 20.60606061])]
[array([0.22727273, 2.32638675, 2.83661291, 3.26988513, 3.4897857 ,
       4.03866756, 4.34203936, 4.34203936, 4.34203936, 4.34203936])]

Leave a ReplyCancel reply