Home > OS >  Dataframe: Columnwise calculations
Dataframe: Columnwise calculations

Time:09-22

I want to import an excel file into a dataframe. My dataframe (without the excel calculations) looks like this:

Jan Feb Mar Apr KPI (IF(SUM(JAN:APR)<0;0);SUM(JAN:APR))
5 -25 -20 5 0
15 24 11 -20 30

What is the best way to calculate the "KPI" column rowwise?

CodePudding user response:

>>> df['KPI']=df.sum(1).mask(lambda x: x<0).fillna(0)

   Jan  Feb  Mar  Apr   KPI
0    5  -25  -20    5   0.0
1   15   24   11  -20  30.0

CodePudding user response:

total = df.loc[:, "Jan": "Apr"].sum(axis=1)
df["KPI"] = total.where(total > 0, other=0)
  • get the total across needed columns
  • keep it as is where it is > 0; put 0 to other places

or

df["KPI"] = np.where(total > 0, total, 0)

or

df["KPI"] = total * (total > 0)
  • Related