Chris90
Chris90

Reputation: 1998

Subtracting from a number value column and limiting the result to zero?

I am trying to see if I can subract a number from a col, but if the number is negative after the subtraction to limit the output to 0 and nothing less or negative.

For ex. col in DF looks like

Mins | new_col
 5.0    2.0
 1.0    0.0
 2.0    0.0
 0.5    0.0
 1.2    0.0
 4.0    1.0

if I want to create a new column that gives me the same values but subtracts 3 from each value in that column.

Upvotes: 0

Views: 532

Answers (4)

user10340258
user10340258

Reputation: 359

It can be solved by simple for loop. Store the input values in list list1.

list2=[] for value in list1: sub=value-3.0 if sub <= 0: list2.append(0.0) else: list2.append(sub) print list2

Upvotes: 0

Chris
Chris

Reputation: 29742

You can use pandas.Series.clip:

df['new_col'] = df['Mins'].sub(3).clip(0)

Upvotes: 1

iamklaus
iamklaus

Reputation: 3770

this solves it.. using np.where

df['new_col'] = np.where(df['Mins']-3 > 0, df['Mins']-3, 0)

Output

   Mins  new_col
0   5.0      2.0
1   1.0      0.0
2   2.0      0.0
3   0.5      0.0
4   1.2      0.0
5   4.0      1.0

Upvotes: 1

Space Impact
Space Impact

Reputation: 13255

You can subtract and then clip using:

df['new_col'] = np.clip(df['Mins']-3, 0, None)
#alternative df['new_col'] = np.clip(df['Mins'].sub(3), 0, None)

Upvotes: 1

Related Questions