Deleting Empty Values in a Mathematica Table

5.1k views Asked by At

I'm importing data from some .asc files in Mathematica using the Import[filename, "Data"] command, and storing it in a table. I've run into a problem where sometimes the .asc files have some empty lines at the end of the file, which result in empty values in the table which causes some problems for me later on.

For instance, when I look at data[[5 ;; (Length[data])]], I get:

{{3446.05, 15.5156}, {3446.18, 14.5156}, ..., {3451.49, 7.51563}, {}, {}, {}, {}}

So my question is: what is the best way to get rid of these empty values? I've looked into either ignoring whitespace in the Import, but haven't found anything that accomplishes that. I've also looked at Delete, but I can't seem to get an expression that matches the empty values.

One way that I can do this is to change Length[data] to 'Length[data]-4`. However, that needs to be potentially changed for each file and I would prefer something that would be a more generalized solution that would work for any file, whether they have whitespace or not.

2

There are 2 answers

7
KennyColnago On

If your imported list were called s, you could use:

s/.{}->Sequence[]

Select[s,Length[#]==2&]

DeleteCases[s,{}]

Partition[Flatten[s],2]
0
Art On

The simplest way is to use the DeleteCases built-in function:

data={{1,2},{},{3,4},{}}

DeleteCases[data,{}]={{1,2},{3,4}}