Appending 2 Tables with different column order and different number of columns
조회 수: 33 (최근 30일)
이전 댓글 표시
Hi,
I need to append tables with different column orders but have the same header for the respecitve columns. For example
A.Properties.VariableNames={'org01','org02','org03','org04',SQ001','SQ002',SQ003'};
B. Properties.VariableNames={'org01','org03','org02',SQ002','SQ003',SQ001'};
How can I append B columns to A columns for the columns that have the same header while assigning for the variables in A that don't have equivalent in B such as org04 NaN values.
댓글 수: 0
채택된 답변
Cris LaPierre
2021년 1월 10일
편집: Cris LaPierre
2021년 1월 10일
MATLAB can use variable names in a table to concatenate two tables even if the order is different. When all the variables are in all tables, use the normal vertical concatenation technique.
It's more challenging if all tables do not have all the variables. MATLAB will fill the unassigned variable(s) with the default value for the datatype. That is 0 for doubles, not NaN (see the warning message below)
% Create 2 tables
org01=(1:5)';
org02=org01;
SQ001=org01;
T1 = table(org01,org02,SQ001)
% Table 2 is a subset of the variable of T1
T2 = flip(T1(:,["SQ001","org01"]))
% Add T2 variable values to T1
T1(end+1:end+height(T2),T2.Properties.VariableNames)=T2
If you really want them to be NaN, there are a couple options. If you want to make all 0s NaN, look into the standardizemissing function. If there will be zeros elsewhere you don't want to change to NaN, you can use a comparison of variable names along with some indexing to set just the extended variables to NaN. Here's an eample.
% Identify the new rows, and just the variables that were not in T2
T1{end-height(T2)+1:end,~ismember(T1.Properties.VariableNames,T2.Properties.VariableNames)}=NaN
댓글 수: 6
Cris LaPierre
2021년 1월 12일
I'm not aware of a way to do this all at once.
You might find the following aswers helpful.
- https://www.mathworks.com/matlabcentral/answers/153538-how-can-i-typecast-a-column-in-a-table-to-a-particular-data-type-in-matlab
- https://www.mathworks.com/matlabcentral/answers/347783-change-table-variable-data-type
- https://www.mathworks.com/matlabcentral/answers/429348-how-to-change-data-type-of-table-in-matlab
Marcus Glover
2024년 2월 24일
편집: Marcus Glover
2024년 2월 24일
Just wanted to add this helped me out and add my last line to anyone looking to remove a row that does not appear in the new table
% Remove rows that were not in T2
T1(:,~ismember(T1.Properties.VariableNames,T2.Properties.VariableNames))=[]
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!