0

Why does the first line work but not the second?

ok:

data_frame['C'] = np.where(np.logical_and(np.greater_equal(data_frame['A'],1), np.not_equal(data_frame['B'],0)), 'OK', '-'  )

not ok:

data_frame['C'] = np.where(data_frame['A']== 1 & data_frame['B']!=0, 'OK', '-')

TypeError: Cannot perform rand_ with a dtyped [float64] array and scalar of type [bool]]

tdy
  • 36,675
  • 19
  • 86
  • 83
haraujo
  • 33
  • 7

1 Answers1

2

It's just the order of operations not being correct if you don't have parens/brackets in the appropriate places. This should work in place of your 2nd variant:

np.where((data_frame['A'] == 1) & 
         (data_frame['B'] != 0), 'OK', '-')

So the comparison operations -- ==, != -- execute before the bitwise one: &.

Edit: this other SO answer explains the order-of-operations thing in more detail -- under the "UPDATE" heading -- in case you need/want that level of explanation: https://stackoverflow.com/a/57922782/42346

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223