我尝试使用convert函数将String转换为float,我使用python3.6:
功能是:
def datatype(s):
it={'N':0,'L':1,'H':2}
return float(it[str(s.strip(), 'utf-8')])
我的数据是 here
当我尝试加载文件时:
d2=np.loadtxt(path2, delimiter=',', skiprows=1, converters={1: datatype, 2:datatype,3:datatype,4:datatype,5:datatype,6:datatype})
它给我错误:
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 '
但我可以手动转换字符串,
>>> datatype(b'L ')
1.0
如何编写转换函数使其没有错误?
答案 0 :(得分:1)
给定的csv中有8列。 你应该提供第8个转换器:
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))