使用numpy在python中读取带有标题的多个CSV文件?

时间:2016-10-10 16:42:25

标签: python

目前我正在使用此代码将一个完整的csv文件读取到我的代码中:

data = np.loadtxt('csv_Complete.csv', delimiter=',', skiprows=1)

但是,现在我有多个这种格式的csv文件。

Log1.csv

x1,x2,x3,x4....
1.5,3,5,7,8
2,5,1.2,5,2
1,3,3,5.5,6

log2.csv

 x1,x2,x3,x4....
 1,3.3,5,7,8
 2,5.1,1,5.5,2
 1,3,3,5,6

这是我正在考虑的方法,但它不起作用。得到一个 ValueError:无法将字符串转换为float:

log1 = np.loadtxt('log1.csv', delimiter=',', skiprows=1)
log2 = np.loadtxt('log2.csv', delimiter=',', skiprows=1)
log3 = np.loadtxt('log3.csv', delimiter=',', skiprows=1)
data = np.append([log1, log2, log3])

我得到的错误是:

 File "<ipython-input-6-6155c8de61ad>", line 1, in <module>
    runfile('C:/Users/Mmyname/.spyder2-py3/setdataexp.py', wdir='C:/Users/myname/.spyder2-py3')

  File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
    execfile(filename, namespace)

  File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/myname/.spyder2-py3/setdataexp.py", line 5, in <module>
    log1 = np.loadtxt('log40a.csv', delimiter=',', skiprows=1)

  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: 

1 个答案:

答案 0 :(得分:1)

文件missing value必须是log40a.csv

我对文件有同样的错误:

x1,x2,x3,x4....
1,3.3,5,7,8
2,5.1,,5.5,2
1,3,3,5,6

如果您缺少值,则以documentation为基础,您应使用genfromtxt function