Python 在给定相同索引和返回匹配数的情况下,检查两个数组中的匹配元素

Python 在给定相同索引和返回匹配数的情况下,检查两个数组中的匹配元素,python,numpy,Python,Numpy,给定两个数组,是否有一种numpy非循环方法来检查数组之间的每个第i个索引是否匹配,即如果a[i]==b[i],是否检查每个i a = np.array([1,2,3,4,5,6,7,8]) b = np.array([2,3,4,5,6,7,8,9]) Output: 0 matches 我想已经有人问过了,但我找不到我要找的东西,如果是,请道歉。试试这个: np.arange(len(a))[a==b] 它创建一个从0到长度a的新数组,表示索引。然后使用a==b对数组进行切片,返回a和

给定两个数组,是否有一种numpy非循环方法来检查数组之间的每个第i个索引是否匹配,即如果a[i]==b[i],是否检查每个i

a = np.array([1,2,3,4,5,6,7,8])
b = np.array([2,3,4,5,6,7,8,9])
Output:  0 matches
我想已经有人问过了,但我找不到我要找的东西,如果是,请道歉。

试试这个:

np.arange(len(a))[a==b]
它创建一个从0到长度
a
的新数组,表示索引。然后使用
a==b
对数组进行切片,返回
a
b
相同的索引

此外,来自@Reblochon Masque:


您可以使用
numpy.where
提取两个值满足指定条件的索引:

import numpy

a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
import numpy

a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
输出: 试试这个:

np.arange(len(a))[a==b]
它创建一个从0到长度
a
的新数组,表示索引。然后使用
a==b
对数组进行切片,返回
a
b
相同的索引

此外,来自@Reblochon Masque:


您可以使用
numpy.where
提取两个值满足指定条件的索引:

import numpy

a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
import numpy

a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
输出:
您可以使用
numpy.where
提取两个值满足指定条件的索引:

import numpy

a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
import numpy

a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
输出:
您可以使用
numpy.where
提取两个值满足指定条件的索引:

import numpy

a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
import numpy

a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
输出:
其他答案的另一个变体:

np.flatnonzero(a == b)

其他答案的另一个变体:

np.flatnonzero(a == b)

您可以尝试以下方法:

a = np.array([1,2,3,2,3,4,3,4,5,6])

b = np.array([8,2,10,2,7,4,10,4,9,8])

np.where(a == b)

(array([1, 3, 5, 7]),)

您可以尝试以下方法:

a = np.array([1,2,3,2,3,4,3,4,5,6])

b = np.array([8,2,10,2,7,4,10,4,9,8])

np.where(a == b)

(array([1, 3, 5, 7]),)

“数组之间的每个第i个索引匹配…”是什么意思?具体来说,您希望这样一个函数返回什么?请查看可能重复的错误措辞,抱歉。检查每个数组中的每个第i个元素,如果a[i]==b[i],那么“…数组之间的每个第i个索引匹配…”是什么意思?具体来说,您希望这样一个函数返回什么?请查看可能重复的错误措辞,抱歉。检查每个数组中的第i个元素,如果a[i]==b[i]谢谢,我试图找出np.where,但不完全正确。正在计算a[np.where(a==b)]和其他不正确的答案。谢谢,我试图找出np.where,但不完全正确。正在计算a[np.where(a==b)]和其他不正确的答案。