【问题标题】:Python compere two rows of different matrixPython比较两行不同的矩阵
【发布时间】:2020-04-16 13:23:41
【问题描述】:

我只想知道如何在 python 中有效地将一个矩阵的一行与另一个矩阵的所有行进行比较。

x=np.array(([-1,-1,-1,-1],[-1,-1,1,1])) #Patterns to be stored
t=np.array(([1,1,1,1])) #test vector
w=0*np.random.rand(4,4)
x_col1=x[0:1].T #Transpose of the 1st row
x_col2=x[1:2].T #Transpose of the second row
w=w+x[0:1].T*x[0]
w=w+x[1:2].T*x[1]
y_in=t*w

这里 x 是一个 2x4 矩阵,y_in 是一个 4x4 矩阵。 我只需要从 x 中剪下一行,然后将其与所有带有 y_in 的行进行比较。

【问题讨论】:

标签: python numpy


【解决方案1】:

以下代码可能会对您有所帮助。

x_row = 1 # Row Index of x you want to check 
i=0
for y_row in y_in:
    print('Row Number:',i+1,(x[x_row]==y_row).all())
    i+=1

【讨论】:

    【解决方案2】:

    假设您有一个形状为 (n,m) 的矩阵 a 和一个形状为 (m,) 的数组 b,并且想要检查 a 的哪一行等于 b 中的一行,您可以使用 np.equal [docs] - 如果您的数据类型是整数。或者 np.isclose [docs] 如果你的数据类型是浮点数 ->

    示例:

    a = np.array([[1,4], [3,4]], dtype=np.float)
    b = np.array([3,4], dtype=np.float)
    
    ab_close = np.isclose(a, b)
    # array([[False,  True],
    #        [ True,  True]])
    
    row_match = np.all(ab_close, axis=1)
    # array([False,  True]) # ...so the second row (index=1) of a is equal to b
    

    ...如果dtype=int,则作为 1-liner:

    row_match = np.all(a==b, axis=1)
    

    ...或其他直接获取行索引的变体(查看this post):

    row_match = np.where((np.isclose(a, b)).all(axis=1))
    # (array([1], dtype=int64),)
    

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多