Alon G
Alon G

Reputation: 35

create column in dataframe pandas, max between column and value

I try to create column in dataframe pandas, max between column and value

const = 10
df['new_val'] = max(df['val']-const, 0)

I get this error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

input:

  val |
   12 |
   5  |

expected:

  val | new_val
   12 |   2
   5  |   0

Upvotes: 0

Views: 40

Answers (2)

jezrael
jezrael

Reputation: 862851

Use numpy.maximum for max per column val:

const = 10
df['new_val'] = np.maximum(df['val'].sub(const), 0)
print (df)
   val  new_val
0   12        2
1    5        0

Or substract values with Series.clip for 0 for negative values:

const = 10
df['new_val'] = df['val'].sub(const).clip(lower=0)
print (df)
   val  new_val
0   12        2
1    5        0

Upvotes: 1

mozway
mozway

Reputation: 260975

If you want to remove const while ensuring not having negative numbers, subtract and clip:

df['new_val'] = df['val'].sub(const).clip(lower=0)

Output:

   val  new_val
0   12        2
1    5        0

Upvotes: 1

Related Questions