-1

I am trying to divide a combined number by 2 if both of the inputs are more than 0

data = {'test':[1,1,0],'test2':[0, 1, 0,]}
df = pd.DataFrame(data)
df['combined'] = df['test'] +df['test2']
df 

I am looking for a way (probably an if-statement to divide df['combined'] by 2 if both test and test2 have a value of 1.

I've tried this, however it gives an error

if ((df['test']> 1) and (df['test2']>1)):
    df['combined'] / 2
else:
    df['combined']

what is the best way to do this?

pepijn
  • 111
  • 7

1 Answers1

0

There are two same kind problems in you if statement. First you should know that result of (df['test']> 1) is a pandas Series object.

0    False
1    False
2    False
Name: test, dtype: bool

Both if and and operation couldn't handle pandas Series object, that's why you see the error.

At last, you can use np.where() to replace Series on condition:

mask = (df['test']> 1) & (df['test2']>1)
df['combined'] = np.where(mask, df['combined'], df['combined'] / 2)
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52