How to read specific numbers (colums) of a csv file

4 次查看(过去 30 天)
I have a csv file with the next format:
  • The first row is a row of strings separated by commas, which indicates the name of each column
  • The next rows are a combination of strings and numeric data.
Here you have a brief description. I just put the first 3 rows, but the rows varies from file to file, so it is unknown.
id,"nodeid","time","power1","apparentPower1","powerFactor1","q1","irms1","power2","apparentPower2","powerFactor2","q2","irms2","power1pluspower2","vrms","t1","devicename"
1,"5",1570147201,237.0,472.0,0.5,407.0,1.86,48.0,177.0,0.27,170.0,0.7,285.0,253.46,29.6,"device1"
2,"5",1570147202,243.0,473.0,0.51,406.0,1.86,51.0,178.0,0.28,170.0,0.7,294.0,253.66,29.6,"device1"
3,"5",1570147203,247.0,475.0,0.51,406.0,1.87,50.0,180.0,0.27,173.0,0.71,297.0,253.99,29.6,"device1"
I need to extract from that set of data, just the columns "time" and "power1" without the header, which would be like columns 3 and 4. I tried this:
data = csvread('test.csv',1,2)
With that code, I avoid to read the first row and start the reading from the second colum, so I also avoid the string "5". The problem is that I get always this error:
Error using dlmread (line 147)
Mismatch between file and format character vector.
Trouble reading 'Numeric' field from file (row number 1, field number 17) ==> ""device1"""\n
Error in csvread (line 48)
m=dlmread(filename, ',', r, c);
I read the documentation and it seem you can delimiter the range putting and additional array in csvread, something like this:
data = csvread('test.csv',1,2,[R1 C1 R2 C2])
The problem is that it does not work. I tried with different combinations, trying to find out how it works but always the same error.
The final result I want to obtain would be something like this, a matrix called 'data' with two colums (time and power) and all the information in files
data =[ 1570147201 237
1570147203 430
1570147203 247
.
.
.
.]
I see this like a simple operation, I checked on internet but I can not do it. I attach a file with the origina data. Can anyone help, please?

回答(2 个)

Ugur Acar
Ugur Acar 2019-10-5

Why dont you read all data instead of just column number 2 and 4, then continue your code just by reading what ever data is needed

  1 个评论
Neko Benítez
Neko Benítez 2019-10-7
How can I do that? Could you give me an brief example please? I thought that csvread just read the file, but it does not work with my example.

请先登录,再进行评论。


Jeremy Hughes
Jeremy Hughes 2019-10-7
I'd do this:
opts = detectImportOptions(filename);
opts.SelectedVariableNames = opts.VariableNames([3 4]);
T = readtable(filename,opts)

类别

Help CenterFile Exchange 中查找有关 Large Files and Big Data 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by