簡體   English   中英

Python:提取與矩陣中非零唯一行相對應的重復行的索引

[英]Python: Extract the indices of repeated rows corresponding to the non-zero unique rows in a matrix

對於此矩陣,K =

 [[1.  2.  3.]
 [ 0.  0.  0.]
 [ 4.  5.  6.]
 [ 0.  0.  0.]
 [ 4.  5.  6.]
 [ 0.  0.  0.]]

如何在矩陣中存儲與非零唯一行相對應的重復行索引的列表/數組。

在此示例中:[0,2]是非零唯一行的索引。

問題:如何在字典中存儲此信息:

   corresponding value for key 0: [0]
   corresponding value for key 2: [2,4]

謝謝!

這是通過collections.defaultdict一種方法。 通過帶有enumeratefor循環進行迭代,並使用set來跟蹤可見的項。

您可以輕松地從末尾的字典中刪除(0, 0, 0) ,並在必要時重命名鍵。 該方法的復雜度為O(n)。

from collections import defaultdict

A = np.array([[ 1,  2,  3],
              [ 0,  0,  0],
              [ 4,  5,  6],
              [ 0,  0,  0],
              [ 4,  5,  6],
              [ 0,  0,  0]])

seen = {(0, 0, 0)}
d = defaultdict(list)

for idx, row in enumerate(map(tuple, A)):
    d[row].append(idx)

結果:

print(d)

defaultdict(list, {(0, 0, 0): [1, 3, 5],
                   (1, 2, 3): [0],
                   (4, 5, 6): [2, 4]})

鑒於您的數據在元組列表中。

data = [
  (1, 2, 3),
  (0, 0, 0),
  (4, 5, 6),
  (0, 0, 0),
  (4, 5, 6),
  (0, 0, 0),
  ]

編輯以回應評論:

將數據轉換為默認字典,然后將索引附加到該字典中每個鍵所附加的列表上。

import collections
output = collections.defaultdict(list)
for i,v in enumerate(data):
  if v == (0,0,0):
    continue
  output[v].append(i)
print(output.values())

輸出為:

[[0], [2, 4]]

原版的

一個簡單的循環就可以了。 這將

  • 忽略(0,0,0)
  • 記錄任何順序的重復集的第一個實例的索引

它將索引存儲在set()以提高性能,但最后將它們排序。

output = set()
lastval = None
lasti = None

for i, val in enumerate(data):
  if val == (0,0,0):
    continue

  if val != lastval:
    lastval = val
    lasti = i

  if lasti not in output:
    output.add(lasti)

print(sorted(output))

輸出是

[0, 2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM