Logical indexing: Find row in table by text in column
조회 수: 196 (최근 30일)
이전 댓글 표시
a = {'hi', 'bye'; 'don', 'tcry' };
t = array2table(a);
u = t(t.a1 == 'don', :); % error: Undefined operator '==' for cell
How do I do a logical search for the row where a1 is 'bye'?
If it was numbers, it would be easy:
b = [1,2 ; 3,4];
q = array2table(b);
r = q(b1 == 3, :); # works perfectly
OK I found one way: Use string().
g = t(string(t.a1)=="don", :); % works! ;-)
Are there other ways, better ways, nicer ways?
댓글 수: 1
채택된 답변
Star Strider
2018년 2월 6일
u = t(strcmp(t.a1, 'don'), :);
u =
1×2 table
a1 a2
_____ ______
'don' 'tcry'
댓글 수: 2
KAE
2019년 6월 20일
Just another way to use Star Strider's solution. If you want the index to the row containing your desired value,
iRow = find(strcmp(t.a1, 'don')==1);
Guillaume
2019년 6월 21일
Note that beginners tend to use find more than they should, you typically see:
indices = find(somearray == somevalue);
result = somerarray(indices);
where find wasn't needed at all and was just a waste of time:
isfound = somearray == somevalue;
result = somearray(isfound);
It's actually rare that you do need the indices.
추가 답변 (4개)
Kristupas Karcemarskas
2022년 4월 17일
I found that it is really easy to use categorise() function
for example:
u=categorise(u);
댓글 수: 0
Peter Perkins
2018년 2월 7일
Two other things worth considering:
1) if {'hi', 'bye'; 'don', 'tcry'} are always unique, consider making them row names. Then t('don', :) is what you would use.
2) If {'hi', 'bye'; 'don', 'tcry'} could be a large list of repeated values, consider making them a categorical vector. Then u = t(t.a1 == 'don', :) is what you would use.
But even if those are not an option, if you are using R2016b or later, consider using a string array instead of a cellstr, as Guillaume says.
댓글 수: 2
Peter Perkins
2018년 2월 12일
To make them row names, it's just
r.Properties.RowNames = t.a1;
t.a1 = []; % delete the original variable
but if the data are coming from a file you may well be able to read them in as row names. See the doc for readtable.
To make a categorical, it's just
t.a1 = categorical(t.a1)
but you will probably want to look over the documentation for categorical arrays. Once t.a1 is categorical, you can use ==. It's not the main reason for using categoricals, but it's a convenience (one that string also provides).
Gabor
2021년 3월 3일
b = [1,2 ; 3,4];
q = array2table(b);
r = q(b1 == 3, :);
Unrecognized function or variable 'b1'.
댓글 수: 1
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!