Home > Enterprise >  two conditions multiplication in pandas
two conditions multiplication in pandas

Time:04-10

I have the following dataframe, and I am trying to get revenue column by a multiplication between columnA or columnB and columnC.

The condition is:

  • if columnB is NaN, then the revenue column = columnA * columnC
  • if columnB is not NaN, then the revenue column = columnB * columnC
type   columnA     columnB     columnC
1        23          NaN          2
2        14          35           3
3        11          NaN          4
4        29          12           5

how do I get this revenue column with these two condition in python? Thanks in advance.

CodePudding user response:

First you can check if columnB contains any NaN values using .isnull().values.any() then apply an if else condition to get the desired revenue column.

Here's how you can do it:

df['revenue'] = df['columnA'] * df['columnC'] if df['columnB'].isnull().values.any() else df['columnB'] * df['columnC']

Output:

   type  columnA  columnB  columnC  revenue
0     1       23      NaN        2       46
1     2       14     35.0        3       42
2     3       11      NaN        4       44
3     4       29     12.0        5      145
  • Related