假设我有一个numpy数组x = [1, 2, 3, 4, 5, ...]
,并且我想用a = [1, 3, 5, ...]
替换列表0
中没有的值。
我尝试了x[x not in a] = 0
,但收到错误消息:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
有人知道不需要说明条件的正确方法吗?
答案 0 :(得分:0)
import numpy as np
x = np.array([1, 2, 3, 4, 5])
a = np.array([1, 3, 5])
x[~np.isin(x,a)] = 0
### Output
>>> array([1, 0, 3, 0, 5])
答案 1 :(得分:0)
您应该使用numpy.where:
x = np.array([1, 2, 3, 4, 5])
a = np.array([1, 3, 5])
mask = np.isin(x, a)
x[mask] = 0
print(x)
>>> array([0, 2, 0, 4, 0])