Create new column in Table based on conditions
16 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Rub Ron
il 26 Lug 2020
Modificato: Rub Ron
il 26 Lug 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);
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Call Python from MATLAB in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!