Python:在将每一行与矩阵中的每一行进行比较后存储非零唯一行的索引

标签 python arrays python-3.x numpy matrix

对于这个矩阵 K=

 [[-1.  1.  0.]
 [ 0.  0.  0.]
 [ 0. -1.  1.]
 [ 0.  0.  0.]
 [ 0. -1.  1.]
 [ 0.  0.  0.]]

任务是将非零唯一行的索引存储在一个数组中(这里的答案是{0,2}),这样

K([0,2],:) 

可用于线性代数运算。 我的尝试是:

myList = []    
for i in range(len(K)): #generate pairs
    for j in range(i+1,len(K)):  #travel down each other rows
        if np.array_equal(K[i],K[j]) and np.any(K[i] != 0, axis=1) and np.any(K[j] != 0, axis=1):
        myList.append(K[i])
        print ('indices of similar-non-zeros rows are\n',(i, j)),
        elif not np.array_equal(K[i],K[j]) and np.any(K[i] != 0,axis=1) and np.any(K[j] != 0, axis=1): 
        myList.append(K[i])
        print ('indices of non-similar-non-zeros rows are\n',(i, j)),
        else: 
            continue

new_K = np.asmatrix(np.asarray(myList))
new_new_K = np.unique(new_K,axis=0)
print('Now K is \n',new_new_K) 

答案是:

    new_new_K = [[-1.  1.  0.]
                 [ 0. -1.  1.]]

问题1:如何用pythonic方式实现。以上是具有矩阵存储限制的替代解决方案,但更可取的是将索引存储在数组中。

最佳答案

为此,您可以使用带有 enumerate 的简单 for 循环。

import numpy as np

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

seen = {(0, 0, 0)}
res = []

for idx, row in enumerate(map(tuple, A)):
    if row not in seen:
        res.append(idx)
        seen.add(row)

结果

print(A[res])

[[-1  1  0]
 [ 0 -1  1]]

示例#2

import numpy as np

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

seen={(0, )*6}

res = []

for idx, row in enumerate(map(tuple, A)):
    if row not in seen:
        res.append(idx)
        seen.add(row)

print(A[res])

# [[0 1 0 0 0 1]
#  [0 0 0 1 0 1]
#  [1 0 1 0 1 1]
#  [1 1 1 0 0 0]
#  [0 1 0 1 0 1]]

关于Python:在将每一行与矩阵中的每一行进行比较后存储非零唯一行的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49857395/

相关文章:

python - 使用 matplotlib.pyplot 时如何显示节点标签?

javascript - 如何从数组中定位当前焦点元素来调用 focusout 函数?

python - 如何将 django admin "view site"链接更改为自定义绝对 url

python - 使用 NumPy 查找所有 n 维直线和对角线

python - 使用 python 进行动态终端打印

python - 训练集和测试集中不同数量的特征 - 随机森林 sklearn Python

python - 组合两个numpy数组以形成一个数组,每个数组中的最大值

c - 通过引用将静态二维结构数组传递给函数

python - 使用开始日期和结束日期进行左连接

python - CSV文件数据组织(结构化数据)