我有一个向量dogSpecies
显示正在调查的所有四种独特的狗种。
#a set of possible dog species
dogSpecies = [1,2,3,4]
我还有一个data
向量,该向量包含与所有受测狗的狗种记录相对应的整数。
# species of examined dogs
data = np.array(1,1,2,-1,0,2,3,5,4)
data
中的某些记录包含的值不同于1,2,3或4(例如-1、0或5)。如果data
中的元素不等于dogSpecies
的任何元素,则应在错误评估布尔矩阵中将此类出现标记为False
。
#initially all the elements of the boolean error evaluation vector are True.
errorEval = np.ones((np.size(data,axis = 0)),dtype=bool)
理想情况下,我的errorEval
向量看起来像这样:
errorEval = np.array[True, True, True, False, False, True, True, False, True]
我想要一段代码来检查data
的元素是否不等于dogSpecies
向量的元素。我的代码出于某种原因将errorEval
向量的每个元素标记为'False'。
for i in range(np.size(data, axis = 0)):
# validation of the species
if (data[i] != dogSpecies):
errorEval[i] = False
我知道我无法将单个元素与上述四个元素的向量进行比较,但是我该怎么做呢?
答案 0 :(得分:1)
这不就是您想要的吗?
for index, elem in enumerate(data):
if elem not in dogSpecies:
errorEval[index] = False
可能不是很快,它不使用任何向量化的numpy ufuncs,但是如果数组不是很大,那就没关系了。将dogSpecies
转换为set
也会加快速度。
顺便说一句,您的python看起来非常c / java风格。我建议您阅读python style guide。
答案 1 :(得分:0)
如果我的理解正确,那么您会有一个数据框和一系列狗的种类。这应该可以实现您想要的。
let array = [ { '231634908': 137875 },
{ '388252786': 150004 },
{ '333624027': 144107 },
{ '382758108': 149729 },
{ '384113458': 149803 },
{ '384844004': 149848 },
{ '405877005': 150481 },
{ '405877005': 150481 } ]
const output = Object.assign({}, ...array)
console.log(output)
如果您不想创建新列,则可以执行以下操作:
df = pd.DataFrame({'dog': [1,3,4,5,1,1,8,9,0]})
dog
0 1
1 3
2 4
3 5
4 1
5 1
6 8
7 9
8 0
df['errorEval'] = df['dog'].isin(dogSpecies).astype(int)
dog errorEval
0 1 1
1 3 1
2 4 1
3 5 0
4 1 1
5 1 1
6 8 0
7 9 0
8 0 0
df.errorEval.values
# array([1, 1, 1, 0, 1, 1, 0, 0, 0])
答案 2 :(得分:0)
如@FHTMitchel所述,您必须使用in
来检查元素是否在列表中。
但是您可以使用列表理解,它比普通循环更快,并且更短:
errorEval = np.array([True if elem in dogSpecies else False for elem in data])