isnan to conver nan to zero in a table

조회 수: 13 (최근 30일)
Darren
Darren 2025년 2월 10일
댓글: Darren 2025년 2월 11일
Hi All,
Apologies for what might be a silly question but I am stuck at the moment.
I have used readtable to input a text formatted CSV file.
T=readtable(zz,'Delimiter', '\t');
This gives a 39x501 table.
The table has NaN values which I need to replace with zeros. Based on anoher answer, I am trying:
T(isnan(T)) = 0;
but get the error
Incorrect number or types of inputs or outputs for function isnan.
Help :-)
Darren

채택된 답변

Steven Lord
Steven Lord 2025년 2월 10일
Let's make a sample table with some NaN values and a non-numeric variable.
A = magic(4);
A(randperm(numel(A), 3)) = NaN;
T = array2table(A);
T.A5 = ["apple"; "banana"; "cherry"; "durian"]
T = 4x5 table
A1 A2 A3 A4 A5 ___ ___ ___ __ ________ NaN 2 3 13 "apple" 5 11 10 8 "banana" 9 NaN NaN 12 "cherry" 4 14 15 1 "durian"
You can use the fillmissing function to replace the NaN values in the numeric variables with the constant 0.
T2 = fillmissing(T, 'constant', 0, 'DataVariables', @isnumeric)
T2 = 4x5 table
A1 A2 A3 A4 A5 __ __ __ __ ________ 0 2 3 13 "apple" 5 11 10 8 "banana" 9 0 0 12 "cherry" 4 14 15 1 "durian"
If all the variables are numeric you can omit the 'DataVariables' name-value argument.
  댓글 수: 1
Darren
Darren 2025년 2월 11일
Thank you very much, that works absolutely fine :-)
All the best,
Darren

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

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2025년 2월 10일
T is an object of the class "table". You can't apply isnan() on it directly. Try the 'TreatAsMissing' option of the readtable() function to avoid NaN first hand.
  댓글 수: 1
Walter Roberson
Walter Roberson 2025년 2월 10일
TreatAsMissing gives additional data patterns that are to have NaN (or appropriate missing indicator) substituted. TreatAsMissing does not give any opportunity to substitute a constant value for missing data.

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

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

태그

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by