5

I'm trying to create a new pandas dataframe column by subtracting an existing dataframe column column from another. However, if the result is a negative number, the new column value should be set to zero.

import pandas as pd
data = {'A': [1,2,3], 'B': [3,2,1]}
df = pd.DataFrame(data)

In [4]: df
Out[4]: 
   A  B
0  1  3
1  2  2
2  3  1

If I create a new dataframe column 'C' by subtracting 'B' from 'A', I get the right result.

df['C'] = df['A'] - df['B']

In[8]: df
Out[7]: 
   A  B  C
0  1  3 -2
1  2  2  0
2  3  1  2

However, if I utilize the max() function to avoid results with a negative number, I get "ValueError: The truth value of a Series is ambiguous."

>>> df['C'] = max(df['A'] - df['B'], 0)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

The expected output is:

   A  B  C
0  1  3  0
1  2  2  0
2  3  1  2

What am I doing wrong?

2
  • what is recommended output? Commented Dec 30, 2015 at 20:32
  • In[8]: df Out[7]: A B C 0 1 3 0 1 2 2 0 2 3 1 2 Commented Dec 30, 2015 at 20:33

4 Answers 4

13

You need to use np.maximum to do element-wise maximum comparison:

>>> np.maximum(df['A'] - df['B'], 0)
0    0
1    0
2    2
dtype: int64

The problem is max is that it essentially checks (df['A'] - df['B']) > 0. This returns an array of boolean values (not a boolean), hence the error.

Sign up to request clarification or add additional context in comments.

Comments

1

Use np.where:

In [8]:
df['C'] = np.where((df['A'] - df['B'] > 0), df['A'] - df['B'], 0)
df

Out[8]:
   A  B  C
0  1  3  0
1  2  2  0
2  3  1  2

the in-built max function operates on scalars not array-like structures hence the error

1 Comment

I used your recommended np.where suggestion somewhere else. Thanks.
0

You could also do apply:

df['C'] = df.apply(lambda row: max(row['A'] - row['B'], 0), axis=1)

Comments

0

Old post, but instead of using the max function:

df.max()

try to apply max-function on the values helped:

df.values.max()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.