Create new column in Table based on conditions
조회 수: 12 (최근 30일)
이전 댓글 표시
Suppose I have a Table object T with 3 columns Price, Units & Cleared. I want to create a new variable called V1 based on condition.
If Cleared == 'yes' then T.Val1 = Price * Units else Price. How can I achieve that? In python I would do something like:
df['Val1'] = np.where(df.Cleared == 'yes', df.price * df.Units, df.Price)
I've just switched from Python to MATLAB and finding it bit difficult to do that. Does MATLAB tables work same way as Pandas in Python? Do tables in MATLAB support vectorized operations?
댓글 수: 0
채택된 답변
Rub Ron
2020년 7월 26일
편집: Rub Ron
2020년 7월 26일
Cleared = {'yes';'no';'yes';'no';'yes'};
Price = [38;43;38;40;49];
Units = [71;69;64;67;64];
T = table(Cleared,Price,Units);
idY =find(strcmp(T.Cleared,'yes'));
idN =find(strcmp(T.Cleared,'no'));
T.V1(idY)=T.Price(idY).*T.Units(idY);
T.V1(idN)=T.Price(idN);
T
T =
5×4 table
Cleared Price Units V1
_______ _____ _____ ____
{'yes'} 38 71 2698
{'no' } 43 69 43
{'yes'} 38 64 2432
{'no' } 40 67 40
{'yes'} 49 64 3136
Alternatively, you also can use this:
idY =strcmp(T.Cleared,'yes');
T.V1 = T.Price.*(1+ (T.Units-1).*idY);
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!