I have a numpy-array "target_tokes" with many values. I try to receive a numpy_array of the same shape, with 1. at a position where in the target_tokens array I had a specific value (i.e. a nine or a two).
This works (for the nine):
i_factor = (target_tokens == 9).astype(np.float32)
Result:
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]...
This does not work:
group = [2, 9]
i_factor = (target_tokens in group).astype(np.float32)
Result is:
i_factor = (target_tokens in group).astype(np.float32)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Why is that and how can I still achieve my result without having big loops (the group is bigger in reality than just two values).
Thx
Like and and or, in isn't allowed to broadcast. The Python language requires that in always returns a boolean. Also, only the right-hand operand can define what in means, and you used a list, not an array. You're getting the in behavior of Python lists.
NumPy's in operator is pretty weird and not useful for you. in for lists makes more sense, but still isn't what you need. You need numpy.isin, which behaves like an in test broadcasted across its left operand (but not its right):
numpy.isin(target_tokens, group).astype(np.float32)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With