Create new column in Table based on conditions

16 次查看(过去 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?

采纳的回答

Rub Ron
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 个)

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by