检查矩阵中的值是否与数组中的值匹配,否则返回矩阵索引

时间:2019-05-11 21:11:26

标签: python arrays numpy matrix

所以我有一个带有数据集的矩阵,我想要一个将矩阵中的所有值与数组进行比较的函数,以检查矩阵中的值是否存在于数组中,如果不存在则返回值的索引。

我尝试在

中设置一个dobbelt for循环
#the array with the values the matrixs values is compared 
Grades=np.array([-3,0,2,4,7,10,12])

#the dobbelt for loop
for u in range(0,len(data)):
        for j in range(0,len(data.T)):
            if not data[u,j] in Grades:
                # Error message is printed if a values isn't a found in the array.
                print("Error in {}, {}".format(u,j))

所有值我都出错了... 错误1,2,错误1,3,错误1,4,错误1,5 ...错误10,4,错误10,5,错误10,6,错误10,7 < / p>

1 个答案:

答案 0 :(得分:0)

由于您没有提供有问题的数据,所以我假设data3*3 matrix,但是此代码适用于每个矩阵。

Grades=np.array([-3,0,2,4,7,10,12])
data = np.array([[1,2,3], [4,5,6], [7,8,9]])

#the dobbelt for loop
for u in range(data.shape[0]):
        for j in range(data.shape[1]):
            if data[u,j] not in Grades:
                # Error message is printed if a values isn't a found in the array.
                print("Error in {} for {} - {}".format(data[u,j], u,j))

输出:

Error in 1 for 0 - 0    # 1 is not present in given array and it's index is (0, 0)
Error in 3 for 0 - 2
Error in 5 for 1 - 1
Error in 6 for 1 - 2
Error in 8 for 2 - 1
Error in 9 for 2 - 2

我希望这可以解决您的查询。