Skip to content
Advertisement

How to create sum of columns in Pandas based on a conditional of multiple columns?

I am trying to sum two columns of the DataFrame to create a third column where the value in the third column is equal to the sum of the positive elements of the other columns. I have tried the below and just receive a column of NaN values

JavaScript

DataFrame:

enter image description here

Advertisement

Answer

You can use df.mask here and fill value less than 0 i.e negative value with 0 and do df.sum over axis 1.

JavaScript

Few NumPy hacks that are useful here.

  • Using np.copyto

    JavaScript
  • Using np.where

    JavaScript
  • Using np.clip

    JavaScript
  • Using np.ma.array

    JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement