【问题标题】:How can I compare two matrices row-wise in python?如何在 python 中逐行比较两个矩阵?
【发布时间】:2020-04-15 02:48:31
【问题描述】:

我有两个列数相同但行数不同的矩阵,一个更大。 matA = [[1,0,1],[0,0,0],[1,1,0]], matB = [[0,0,0],[1,0,1],[0,0,0],[1,1,1],[1,1,0]]

它们都是numpy矩阵

我试图找出 matA 的每一行出现在 matB 中的次数,并将其放入一个数组中,这样在这种情况下的数组将变为 arr = [1,2,1],因为 matA 的第一行出现了一次在 matB 中,第二行出现了两次,最后一行只出现了一次

【问题讨论】:

  • 会不会是 B 中有元素不在 A 中?然后我需要在我的回答中处理这个问题。

标签: python matrix compare row


【解决方案1】:

Find unique rows in numpy.array

What is a faster way to get the location of unique rows in numpy

这是一个解决方案:

import numpy as np

A = np.array([[1,0,1],[0,0,0],[1,1,0]])

B = np.array([[0,0,0],[1,0,1],[0,0,0],[1,1,1],[1,1,0]])

# stack the rows, A has to be first
combined = np.concatenate((A, B), axis=0) #or np.vstack

unique, unique_indices, unique_counts = np.unique(combined,
                                                  return_index=True,
                                                  return_counts=True,
                                                  axis=0) 

print(unique)
print(unique_indices)
print(unique_counts)

# now we need to derive your desired result from the unique
# indices and counts

# we know the number of rows in A
n_rows_in_A = A.shape[0]

# so we know that the indices from 0 to (n_rows_in_A - 1)
# in unique_indices are rows that appear first or only in A

indices_A = np.nonzero(unique_indices < n_rows_in_A)[0] #first 
#indices_A1 = np.argwhere(unique_indices < n_rows_in_A) 
print(indices_A)
#print(indices_A1)

unique_indices_A = unique_indices[indices_A]
unique_counts_A = unique_counts[indices_A]

print(unique_indices_A)
print(unique_counts_A)

# now we need to subtract one count from the unique_counts
# that's the one occurence in A that we are not interested in.

unique_counts_A -= 1
print(unique_indices_A)
print(unique_counts_A)

# this is nearly the result we want
# now we need to sort it and account for rows that are not
# appearing in A but in B

# will do that later...

【讨论】:

    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2012-10-20
    相关资源
    最近更新 更多