Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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'
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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
over 4 years ago · Santiago Trujillo Relatório

0

You can use np.where:

import numpy as np
df['cost'] = np.where(df['status']=='online', df['price']*metric, 0)
over 4 years ago · Santiago Trujillo Relatório

0

If you want plain pandas you can use loc:

df['cost'] = 0
df.loc[df['status']== "online" , 'cost'] = df['price'] * metric

Or with a list comprehension:

df['cost'] = [df['price']*metric if status == 'online' else 0 for status in df['status']]
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda