Create new column in Table based on conditions

16 ビュー (過去 30 日間)
Furqan Hashim
Furqan Hashim 2020 年 7 月 26 日
編集済み: Rub Ron 2020 年 7 月 26 日
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 Center および File ExchangeCall 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