Create new column in Table based on conditions

8 views (last 30 days)
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?

Accepted Answer

Rub Ron
Rub Ron on 26 Jul 2020
Edited: Rub Ron on 26 Jul 2020
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);

More Answers (0)

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!