简体   繁体   English

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

[英]Reading multiple CSV files with headers in python with numpy?

Currently I am using this code to read one complete csv file to my code:目前我正在使用此代码将一个完整的 csv 文件读取到我的代码中:

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

However, Now I have multiple csv files that are in this format.但是,现在我有多个这种格式的 csv 文件。

Log1.csv日志1.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日志2.csv

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

This is the method I am thinking of doing but it is not working.这是我正在考虑做的方法,但它不起作用。 Getting a ValueError: could not convert string to float:获取 ValueError:无法将字符串转换为浮点数:

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])

The error I am getting is:我得到的错误是:

 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: 

It must be a missing value in file log40a.csv .它必须是文件log40a.csvmissing value

I have the same error for file like:我对文件有同样的错误,如:

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

Base on documentation if you have missing values you should use genfromtxt function .根据文档,如果您有缺失值,您应该使用genfromtxt 函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM