user504909
user504909

Reputation: 9549

covert error for loadtxt function

I try to use convert function to convert String to float, I use python3.6:

the function is:

def datatype(s):
    it={'N':0,'L':1,'H':2}
    return float(it[str(s.strip(), 'utf-8')])

My data is here

When I try to load the file:

d2=np.loadtxt(path2, delimiter=',', skiprows=1, converters={1: datatype, 2:datatype,3:datatype,4:datatype,5:datatype,6:datatype})

it give me error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 930, in loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "C:\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 930, in <listcomp>
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "C:\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 659, in floatconv
return float(x)
ValueError: could not convert string to float: b'L '

but I can convert string manually,

>>> datatype(b'L ')
1.0

How to write convert function make it no error?

Upvotes: 1

Views: 625

Answers (1)

falsetru
falsetru

Reputation: 368894

There are 8 columns in the given csv. You should provide 8th converter:

d2 = np.loadtxt(path2, delimiter=',', skiprows=1, converters={
    1: datatype, 2: datatype, 3: datatype, 4: datatype,
    5: datatype, 6: datatype, 7: datatype,
})

OR

d2 = np.loadtxt(path2, delimiter=',', skiprows=1,
                converters=dict.fromkeys(range(1, 8), datatype))

Upvotes: 1

Related Questions