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

标签 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 错误

最佳答案

由于您没有提供相关数据,因此我假设 data3*3 矩阵,但此代码适用于每个矩阵。

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

我希望这能解决您的疑问。

关于python - 检查矩阵中的值是否与数组中的值匹配,如果不匹配则返回矩阵索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094312/

相关文章:

python - 如何使用子图更改图形大小?

arrays - 在 ruby​​ 中,对于二维数组,如何删除与一个值不同的另一行匹配的行?

javascript - 如何更改 AngularJS 中二维数组的属性?

python-3.x - 将 Numpy 结构数组保存到 *.mat 文件

python - 如何创建一个 numpy 数组,其元素是其他 numpy 数组对象?

python - Networkx 的有效学位序列是什么

Python pandas 时间序列插值日期时间数据

c - 在 C 中分配二维数组的更好做法是什么

python - 将格式错误的 csv 文件转换为 numpy 数组

python - 在数据框中添加新行,并有条件分割前一行