How can I replace NaN in a table with a zero?

조회 수: 36 (최근 30일)
Elyse
Elyse 2024년 6월 20일
댓글: Elyse 2024년 6월 20일
I have a table in MatLab titled data, and there are NaN values in the first couple rows of the table. I would like to change these values to zero, but any way I've tried gives an error message because it is a table and not a matrix or array. If anyone has a way to change these values it would be greatly appreciated! Thanks!

채택된 답변

R
R 2024년 6월 20일
Hi @Elyse,
If you're working with a table in MATLAB and you want to replace NaN values with zeros, you'll need to handle the data column-wise or cell-wise depending on the data type of each column in the table.
You need to iterate over each column, check data type if replacing NaN makes sense or is necessary and then use logical indexing or isnan function for it.
Here's a sample code that demonstrates the same:
% Sample table
Age = [NaN; 22; NaN; 45];
Salary = [NaN; 55000; 60000; NaN];
Name = ["John Doe"; "Jane Doe"; "Alice"; "Bob"];
T = table(Age, Salary, Name);
disp('Original Table:');
Original Table:
disp(T);
Age Salary Name ___ ______ __________ NaN NaN "John Doe" 22 55000 "Jane Doe" NaN 60000 "Alice" 45 NaN "Bob"
% Loop through each variable in the table
for varName = T.Properties.VariableNames
% Get the column data
columnData = T.(varName{1});
% Check if the column is numeric
if isnumeric(columnData)
% Replace NaN with 0
columnData(isnan(columnData)) = 0;
% Assign the modified column back to the table
T.(varName{1}) = columnData;
end
% For non-numeric data, you can define other replacements if necessary
end
disp('Modified Table:');
Modified Table:
disp(T);
Age Salary Name ___ ______ __________ 0 0 "John Doe" 22 55000 "Jane Doe" 0 60000 "Alice" 45 0 "Bob"
Hope it helps!
  댓글 수: 1
Elyse
Elyse 2024년 6월 20일
Thanks, using just the one line:
columnData(isnan(columnData)) = 0;
worked for me without the loop

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Torsten
Torsten 2024년 6월 20일

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by