Axel
Axel

Reputation: 1475

How to properly remove NaN values from table

After reading an Excel spreadsheet in Matlab I unfortunately have NaNs included in my resulting table. So for example this Excel table:

Excel table

would result in this table:

Matlab table

where an additional column of NaNs occurs. I tried to remove the NaNs with the following code snippet:

measurementCells = readtable('MWE.xlsx','ReadVariableNames',false,'ReadRowNames',true);
measurementCells = measurementCells(any(isstruct(measurementCells('TIME',1)),1),:);

However this results in a 0x6 table, without any values present anymore. How can I properly remove the NaNs without removing any data from the table?

Upvotes: 4

Views: 3191

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

Either this:

tab = tab(~any(ismissing(tab),2),:);

or:

tab = rmmissing(tab);

if you want to remove rows that contain one or more missing value.

If you want instead to replace missing values with other values, read about how fillmissing (https://mathworks.com/help/matlab/ref/fillmissing.html) and standardizeMissing (https://mathworks.com/help/matlab/ref/standardizemissing.html) functions work. The examples are exhaustive and should help you to find the solution that best fits your needs.

One last solution you have is to spot (and manipulate in the way you prefer) NaN values within the call to the readtable function using the EmptyValue parameter. But this works only against numeric data.

Upvotes: 2

Related Questions