1

I am pretty new to Python and I am trying to create a column in my pandas df using pre-exisitng columns (code below).

if ((df['a'] != -1) & (df['b'] == -1)):
    df['c'] = df['a']
elif ((df['a'] == -1 ) & (df['b'] != -1)):
    df['c'] = df['b']    
else: 
    df['c'] = 0

However, I keep getting the following error:

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

When I add '.any()', it still does not perform as needed. Am I totally off with this?

aapal
  • 13
  • 4
  • Use `np.where`. Understand that `db['a'] == -1` returns a series of booleans rather than a single one, which is what your code is set up to expect – ifly6 Oct 06 '20 at 13:49

1 Answers1

0
df = pd.DataFrame( {'a': [-1, 1, 1, -1], 'b': [1, 1, -1, -1]})

df['c'] = 0
df.loc[(df['a'] != -1) & 
       (df['b'] == -1), 'c'] = df[(df['a'] != -1) & (df['b'] == -1)]['a'] 

df.loc[(df['a'] == -1) & 
       (df['b'] != -1), 'c'] = df[(df['a'] == -1) & (df['b'] != -1)]['b'] 

print (df)

Output:

   a  b  c
0 -1  1  1
1  1  1  0
2  1 -1  1
3 -1 -1  0

OR

df['c'] = df.apply(lambda r: 
                   r['a'] if r['a'] != -1 and r['b'] == -1 else (
                       r['b'] if r['a'] == -1 and r['b'] != -1 else 0), 
                   axis=1)
mujjiga
  • 16,186
  • 2
  • 33
  • 51