【问题标题】:Python: loop over a matrix to check for all values in a vectorPython:遍历矩阵以检查向量中的所有值
【发布时间】:2020-06-22 16:45:57
【问题描述】:

我有这个向量:possibleGrades=np.array([-3,0,2,4,7,10,12])

我想让计算机告诉我在这个矩阵中哪里有不是来自向量的值:

    [[ 7.   7.   4. ]
 [12.  10.  10. ]
 [-3.   7.   2. ]
 [10.   8.  12. ]
 [ nan  7.   nan]
 [ 7.   7.  10. ]
 [ 4.5  nan  2. ]
 [ 2.  12.   4. ]]

我的想法:

for i in range(matrixGr):
    if (-3) in matrixGr:
        pass
    elif 0 in matrixGr:
        pass
    elif 2 in matrixGr:
        pass
    elif 4 in matrixGr:
        pass
    elif 7 in matrixGr:
        pass
    elif 10 in matrixGr:
        pass
    elif 12 in matrixGr:
        pass
    else:
        print("The data set contains incorrect grades at {location?}!")

但这是不可能的,如何做到这一点超出了我的心理承受能力。

什么是聪明可行的方法?

如果可以说“行 X 包含无效的 8 级(例如)”,那就太好了,所以带有字符串“行 {:s} 的东西有无效的等级 {:s}”和 .format( “聪明的东西”)

有人可以帮忙吗?

【问题讨论】:

    标签: python arrays pandas numpy vector


    【解决方案1】:

    你可以试试这个:

    import numpy as np
    
    possibleGrades = np.array([-3, 0, 2, 4, 7, 10, 12])
    
    matrixGr = np.array([[7, 7, 4],
                       [12, 10, 10],
                       [-3, 7, 2],
                       [10, 8, 12],
                       [np.nan, 7, np.nan],
                       [7, 7, 10],
                       [4.5, np.nan, 2],
                       [2, 12, 4]])
    
    locations = [(i, j) for i in range(matrixGr.shape[0]) for j in range(matrixGr.shape[1]) if matrixGr[i, j] not in possibleGrades]
    
    locations:
    [(3, 1), (4, 0), (4, 2), (6, 0), (6, 1)]
    

    祝你好运!

    【讨论】:

      【解决方案2】:

      也许你可以试试这个:

      possibleGrades = np.array([-3,0,2,4,7,10,12])
      matrix = np.array([
          [ 7. ,  7.,   4. ],
          [12.,  10.  ,10. ],
          [-3.,   7.  , 2. ],
          [10.,   8.  ,12. ],
          [ np.nan,  7.  , np.nan],
          [ 7. ,  7.  ,10. ],
          [ 4.5,  np.nan , 2. ],
          [ 2. , 12.,   4. ]
      ])
      line, col = np.where(np.isin(matrix, possibleGrades, invert=True))
      print('locations:')
      [print(f'Invalid value {matrix[line[i],col[i]]} at location ({line[i]},{col[i]})') for i in range(line.size)]
      

      你应该得到结果:

      locations:
      Invalid value 8.0 at location (3,1)
      Invalid value nan at location (4,0)
      Invalid value nan at location (4,2)
      Invalid value 4.5 at location (6,0)
      Invalid value nan at location (6,1)
      
      • np.isin:在向量中查找元素,但选项 invert=True 可以反转结果。
      • np.where: 查找 True 元素对应的行和列。

      【讨论】:

      • 谢谢!这很有帮助!现在我有一个后续问题:` line, col = np.where(np.isin(matrixGrades, possibleGrades, invert=True)) print('显示不正确或缺失的成绩:\n') [print(f'不正确或在第 {col[i]} 列中的第 {line[i]} 行中缺少成绩!显示不正确的成绩:{INSERT VALUE}.') for i in range(line.size)]` 我该怎么做?所以它显示不正确的行中的值?我试过matrix[i]但不起作用。我也想知道,我可以以某种方式进行编辑,使其不以第 1 行为 0 开头,但实际上第 1 行和第 1 列是 1 而不是第 0 列?
      • 我编辑了答案。要从值 one 开始,您可以将一个添加到 line 和 col 数组,以便 (1,1) 对应于第一个元素。
      【解决方案3】:

      这是一个简单的 oneliner,它使用列表推导和 enumerate() 函数返回不在“goodgrades”列表中的索引:

      goodgrades = [-3,0,2,4,7,10,12]
      testgrades = [10,-3,11]
      badgrades = [ind for ind, i in enumerate(testgrades) if i not in goodgrades]
      

      testgrades = [7,10,7] 不返回任何内容,而 [7,-1,7] 返回 [1]。

      要将其扩展为成绩列表列表,您可以将其用作函数:

      def checkgrades(grades):
          return [ind for ind, i in enumerate(grades) if i not in goodgrades]
      

      现在,您可以循环使用它并逐行打印测试结果:

      for row in range(len(grades)):
          badgrades = checkgrades(grades[row])
          if badgrades != []:
              print('Bad grades found in row {} at indices {}'.format(row, badgrades))
      

      【讨论】:

      • 注意:虽然这种方法比 Robustus 的答案更冗长,但这适用于每个成绩子列表具有不同数量的成绩的列表。这两种方法都很有价值,取决于你需要什么!
      【解决方案4】:

      这是一个单行函数,它返回一个与matrixGr 大小相同的布尔矩阵,如果成绩在possibleGrades 中则返回 True,否则返回 False:

      >>> np.any(np.stack([grade==matrixGr for grade in possibleGrades]),axis=0)
      array([[ True,  True,  True],
             [ True,  True,  True],
             [ True,  True,  True],
             [ True, False,  True],
             [False,  True, False],
             [ True,  True,  True],
             [False, False,  True],
             [ True,  True,  True]])
      

      如果你想要相反,只需在其周围添加np.logical_not()

      >>> np.logical_not(np.any(np.stack([e==mat for e in possibleGrades]),axis=0))
      array([[False, False, False],
             [False, False, False],
             [False, False, False],
             [False,  True, False],
             [ True, False,  True],
             [False, False, False],
             [ True,  True, False],
             [False, False, False]])
      

      简而言之,它的作用是为possibleGrades 中的每个年级构建一个布尔矩阵,然后汇总所有结果。

      【讨论】:

        猜你喜欢
        • 2011-05-18
        • 2013-04-07
        • 2020-01-23
        • 2022-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-13
        相关资源
        最近更新 更多