Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new column based on a condition

I have a dataframe df, need to create a new column, which is a product of price with metric(int calculated before).

df['cost'] = df['price'] * metric if (df['status'] == 'online')
df['cost'] = 0 if df['status'] == 'offline'
like image 921
Costa Avatar asked Dec 10 '22 23:12

Costa


1 Answers

We can leverage the point that True is 1 and False is 0 when used in multiplication.

3 * True  -> 3
3 * False -> 0

We have to check if values are equal to online in the status column.

df['cost'] = df['price'] * df['status'].eq('online') * metric

Wherever, status is offline cost value is 0.


The above solution relies on the fact you want to set offline values to 0. If you want to set offline to let's 999. Then we can use Series.where here.

df['cost'] = df['price'].mul(metric).where(df['status'].eq('online'), 999)

Now, every offline value to set to 999.

Useful links:

  • Series.where
  • Series.eq
  • Series.mul
  • Multiplying boolean with float
like image 104
Ch3steR Avatar answered Jan 03 '23 05:01

Ch3steR