簡體   English   中英

python中的矩陣COUNT + GROUP BY

[英]Matrix COUNT + GROUP BY in python

我有一個用整數填充的向量矩陣。 例如:

[[1, 2, 3],
 [2, 3, 1],
 [1, 2, 3],
 [2, 3, 1],
 [2, 3, 1]]

我想計算所有可區分的向量,以獲得類似這樣的結果:

[[2, [1, 2, 3]],
 [3, [2, 3, 1]]]

首先,我有出現的次數,然后是向量。

在SQL中,可以使用COUNT + GROUP BY完成。

但是,如何使用python“智能”計算它?

僅限於Python,您可以使用Counter

from collections import Counter

matrix = [[1, 2, 3],
          [2, 3, 1],
          [1, 2, 3],
          [2, 3, 1],
          [2, 3, 1]]
c = Counter(map(tuple, matrix))
result = [[count, list(row)] for row, count in c.items()]
print(result)
# [[2, [1, 2, 3]], [3, [2, 3, 1]]]

使用NumPy,您可以使用np.unique

import numpy as np

matrix = np.array([[1, 2, 3],
                   [2, 3, 1],
                   [1, 2, 3],
                   [2, 3, 1],
                   [2, 3, 1]])
rows, counts = np.unique(matrix, axis=0, return_counts=True)
result = [[count, list(row)] for row, count in zip(rows, counts)]
print(result)
# [[2, [1, 2, 3]], [3, [2, 3, 1]]]

首先將m的每個子列表轉換為元組。 然后使用collections.Counter對主列表中元組的出現進行計數。 現在使用鍵(無計數)和值(元組)遍歷此計數器對象,並將它們附加到新列表中,如下所示:

from collections import Counter
m = [[1, 2, 3],
 [2, 3, 1],
 [1, 2, 3],
 [2, 3, 1],
 [2, 3, 1]]
m = map(tuple, m)
l = []
for k,v in Counter(m).items():
    l.append([v, list(k)])

輸出

[[2, [1, 2, 3]], [3, [2, 3, 1]]]

注意: Counter(m)產生以下計數器對象:

Counter({(2, 3, 1): 3, (1, 2, 3): 2})

我使用鍵值對的哈希圖(它是字典)來記錄值。 這將產生一個字典,但是如果需要,可以將其重新排列為列表。

我認為僅通過引用字典中的鍵,返回元素出現在列表中的次數將變得更加容易。

nested_array = [[1, 2, 3],
 [2, 3, 1],
 [1, 2, 3],
 [2, 3, 1],
 [2, 3, 1]]

hashmap ={}

for element in nested_array:
    d=repr(element)
    if d not in hashmap:
        d=repr(element)
        hashmap[d]=1
    elif d in hashmap:
        hashmap[d] += 1

print(hashmap)

這是輸出: 在此處輸入圖片說明

暫無
暫無

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

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