Replacing Negative Values in Table with Previous Value in Column

조회 수: 11 (최근 30일)
Stef1998
Stef1998 2021년 11월 22일
답변: Peter Perkins 2021년 11월 23일
I have a table 17520x5, in the last 2 columns I would like to replace all negative values with the previous value in that column. This is what I have tried so far and it is not working I still get negative values shown.
My table (T) had 5 columns, variable labels are (A, B, C, D, E) for each column for example
D(D < 0) = NaN;
E(E < 0) = NaN;
T(:, {'D', 'E'}) = fillmissing(T(:,{'D', 'E'}), 'previous');
disp(T)

채택된 답변

Matt J
Matt J 2021년 11월 22일
편집: Matt J 2021년 11월 22일
T(:, {'D', 'E'}) = num2cell( fillmissing([D,E], 'previous') );
  댓글 수: 3
Matt J
Matt J 2021년 11월 22일
편집: Matt J 2021년 11월 22일
We can try an example to show that it works:
T=array2table( rand(4,5)-0.5 ,'Var',{'A','B','C','D','E'});
D=T{:,4}; E=T{:,5};
D(D < 0) = NaN;
E(E < 0) = NaN;
T,
T = 4×5 table
A B C D E _______ ________ ________ ________ ________ 0.44208 0.49326 0.12868 0.42218 0.43518 0.24954 -0.42086 -0.39169 -0.31886 -0.13442 0.38232 -0.3545 -0.49562 -0.47566 -0.15402 0.28615 0.3741 0.11841 -0.16468 0.48483
T(:, {'D', 'E'}) = num2cell( fillmissing([D,E], 'previous') )
T = 4×5 table
A B C D E _______ ________ ________ _______ _______ 0.44208 0.49326 0.12868 0.42218 0.43518 0.24954 -0.42086 -0.39169 0.42218 0.43518 0.38232 -0.3545 -0.49562 0.42218 0.43518 0.28615 0.3741 0.11841 0.42218 0.48483
Stef1998
Stef1998 2021년 11월 22일
Thank you so much! It worked

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

추가 답변 (1개)

Peter Perkins
Peter Perkins 2021년 11월 23일
Stef, as near as I can tell, the only thing wrong with your original solution is that D and E are in T, not in the workspace. The following works fine, including repeated negative values and negative values in the first row. There's no need to explicitly pull D and E out of the table. Using Matt's setup:
>> T = array2table(rand(4,5)-0.5 ,'Var',["A" "B" "C" "D" "E"])
T =
4×5 table
A B C D E
________ ________ _________ ________ _________
-0.33782 -0.33435 0.18921 -0.27102 0.038342
0.29428 0.10198 0.24815 0.41334 0.49613
-0.18878 -0.23703 -0.049458 -0.34762 -0.42182
0.028533 0.15408 -0.41618 0.32582 -0.057322
>> T.D(T.D < 0) = NaN;
>> T.E(T.E < 0) = NaN
T =
4×5 table
A B C D E
________ ________ _________ _______ ________
-0.33782 -0.33435 0.18921 NaN 0.038342
0.29428 0.10198 0.24815 0.41334 0.49613
-0.18878 -0.23703 -0.049458 NaN NaN
0.028533 0.15408 -0.41618 0.32582 NaN
>> T(:, ["D" "E"]) = fillmissing(T(:,["D" "E"]), 'previous')
T =
4×5 table
A B C D E
________ ________ _________ _______ ________
-0.33782 -0.33435 0.18921 NaN 0.038342
0.29428 0.10198 0.24815 0.41334 0.49613
-0.18878 -0.23703 -0.049458 0.41334 0.49613
0.028533 0.15408 -0.41618 0.32582 0.49613

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by