虽然类似的问题已经提出了几次,但我仍然无法在Python中创建类似于matlab ismember函数的函数.特别是,我想在循环中使用这个函数,并在每次迭代中将整个矩阵与另一个矩阵的元素进行比较.在发生相同值的情况下,我想打印1,在任何其他情况下打印0.
假设我有以下矩阵
d = np.reshape(np.array([ 2.25, 1.25, 1.5 , 1. , 0. , 1.25, 1.75, 0. , 1.5 , 0. ]),(1,10))
d_unique = np.unique(d)
Run Code Online (Sandbox Code Playgroud)
然后我有
d_unique
array([ 0. , 1. , 1.25, 1.5 , 1.75, 2.25])
Run Code Online (Sandbox Code Playgroud)
现在我想迭代
J = np.zeros(np.size(d_unique))
for i in xrange(len(d_unique)):
J[i] = np.sum(ismember(d,d_unique[i]))
Run Code Online (Sandbox Code Playgroud)
以便作为输出:
J = [3,1,2,2,1,1]
Run Code Online (Sandbox Code Playgroud)
有人有任何想法吗?提前谢谢了.
Yuv*_*mon 10
与其他答案相比,numpy有内置的numpy.in1d来做到这一点.
用法:
bool_array = numpy.in1d(array1, array2)
Run Code Online (Sandbox Code Playgroud)
注意:它还接受列表作为输入.