How to filter table rows according different conditions?
조회 수: 219 (최근 30일)
이전 댓글 표시
Hi guys, I have a large table with 4480 rows and I need to filter them to mantain only rows matching a given condition.
clear all; close all; clc;
%Data import
file_name = 'NHATS_data.csv';
NHATS_table = readtable(file_name,"VariableNamingRule","preserve");
filt_cnd = strcmp(NHATS_table.Object,'(2020 HO5)');
% Other conditons on object names:
% ||... || (2021 GM1) || (2021 LF6) || (2020 CD3)
% || (2020 FA1) || (2020 HF4) || (2020 MU1) || (2020 WY)
% || (2021 AK5) || (2021 RZ3) || (2021 RG12) || (2022 BY39)
%Data filtering
NHATS_table_filtered = NHATS_table(filt_cnd,:)
I need to mantain all the rows that contains the objects whose names are the commentend ones. Up to now I managed to impose the condition on a single object name, can you help me to code in way that I can impost contemproary all the conditons?
Thanks in advance
댓글 수: 0
채택된 답변
Steven Lord
2022년 10월 3일
You can do this using ismember or (depending on your conditions) some of the string processing functions like matches, contains, startsWith, endsWith, etc.) Let's make a sample table.
load patients
T = table(LastName, Age);
Let's look for all patients whose names are Smith or Jones. For this I'll use ismember.
T(ismember(T.LastName, ["Smith", "Jones"]), :)
How about all patients whose names start with J?
T(startsWith(T.LastName, 'J'), :)
Starts with B or ends with r? For this we need to combine startsWith and endsWith.
T(startsWith(T.LastName, 'B') | endsWith(T.LastName, 'r'), :)
댓글 수: 0
추가 답변 (1개)
dpb
2022년 10월 3일
NHATS_table = readtable(file_name,"VariableNamingRule","preserve");
NHATS_table.Object=categorical(NHATS_table.Object); % convert to categorical (several others probably should be as well...)
WANTLIST={'(2020 HO5)','(2021 GM1)','(2021 LF6)','(2020 CD3)','(2020 FA1)','(2020 HF4)','(2020 MU1)','(2020 WY)'};
NHATS_table_filtered = NHATS_table(ismember(NHATS_table.Object,WANTLIST),:);
NB: It may not be necessary to actually create the second table but use groupfilter with the given group.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 String Parsing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!