MATLAB和Python都提供了函数或对象的方法对表或DataFrame的行数据进行筛选。根据参与筛选的列的个数,可以有单条件筛选和多条件筛选。
MATLAB提供了rowfilter函数结合表的布尔索引对行数据进行筛选。下面创建一个表T。
code.matlab
>> T=table({'张三';'李四';'杨二';'王五'},[18;19;17;25],...
[162;169;162;167], [116;103;131;133],'VariableNames',...
{'Name' 'Age' 'Height' 'Weight'});
用rowfilter函数创建一个关于表T的筛选对象。
code.matlab
>> rf=rowfilter(T);
使用布尔索引筛选出年龄大于或等于19岁的行数据。
code.matlab
>> T(rf.Age>=19,:)
ans =
2×4 table
Name Age Height Weight
________ ___ ______ ______
{'李四'} 19 169 103
{'王五'} 25 167 133
对于多条件筛选的情况,下面筛选出年龄大于或等于18岁,身高大于162厘米的行数据。
code.matlab
>> T(rf.Age>=18 & rf.Height>162,:)
ans =
2×4 table
Name Age Height Weight
________ ___ ______ ______
{'李四'} 19 169 103
{'王五'} 25 167 133
下面使用vartype函数结合表索引筛选出表中的数值类型的数据。
code.matlab
>> S=vartype('numeric');
>> T2=T(:,S)
T2 =
4×3 table
Age Height Weight
___ ______ ______
18 162 116
19 169 103
17 162 131
25 167 133