Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

two conditions multiplication in pandas

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading