Reorder table columns names

19 ビュー (過去 30 日間)
Sarah Yun
Sarah Yun 2019 年 12 月 15 日
回答済み: Naruepon Weerawongphrom 2024 年 11 月 6 日
Hi,
I have two tables
The order of the columns in the 1st table is:
Date, temp, humidity, pressure, precip, depth
The order of the columns in the 2nd table is:
Date, pressure, temp, humdity, precip, depth
How can I change the order of the 2nd table column names to match the order of the 1st table column names?
Thank you.

採用された回答

Adam Danz
Adam Danz 2019 年 12 月 15 日
編集済み: Adam Danz 2019 年 12 月 15 日
Hint:
[~, newOrder] = ismember(T1.Properties.VariableNames,T2.Properties.VariableNames);
Or, as Steven Lord points out in the comments below, you can use the VariableNames of Table 1.
  2 件のコメント
Adam Danz
Adam Danz 2019 年 12 月 15 日
Looks like you got the hint! :)
In case future visitors are interested, here's the full demo:
% Create two tables
T1 = array2table(rand(10,6),'VariableNames',{'Date', 'temp', 'humidity', 'pressure', 'precip', 'depth'});
T2 = array2table(rand(10,6),'VariableNames',{'Date', 'pressure', 'temp', 'humidity', 'precip', 'depth'});
% Determine new column order of table 2
[~, newOrder] = ismember(T1.Properties.VariableNames,T2.Properties.VariableNames);
% Reorder columns of table 2
T2New = T2(:,newOrder)
Steven Lord
Steven Lord 2019 年 12 月 15 日
Once you check (or if you can assume) that T2 has all the variables T1 does, you could skip ismember.
T3 = T2(:, T1.Properties.VariableNames);

サインインしてコメントする。

その他の回答 (2 件)

Image Analyst
Image Analyst 2019 年 12 月 15 日
Try using table():
% Make random values for Date, temp, humidity, pressure, precip, depth
Date = randi(100, [5, 1]);
temp = randi(100, [5, 1]);
humidity = randi(100, [5, 1]);
pressure = randi(100, [5, 1]);
precip = randi(100, [5, 1]);
depth = randi(100, [5, 1]);
% Create tables, T1 and T2, as containers for the workspace variables.
T1 = table(Date, temp, humidity, pressure, precip, depth)
T2 = table(Date, pressure, temp, humidity, precip, depth ) % A different order
% Reorder T2's columns to have variables in the same order as T1.
% This assumes that all variable names exist in both tables and no extra or missing ones.
T2Sorted = table(T2.Date, T2.temp, T2.humidity, T2.pressure, T2.precip, T2.depth, ...
'VariableNames', {'Date', 'temp', 'humidity', 'pressure', 'precip', 'depth'})

Naruepon Weerawongphrom
Naruepon Weerawongphrom 2024 年 11 月 6 日
T2new = movevars(T2,'pressure','Before','temp');

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by