如何按列计算每个唯一元素的出现次数?

huangapple go评论68阅读模式
英文:

How to count occurrences for each unique element by column?

问题

以下是翻译好的部分:

我有一个二维数组,并想获取每列所有唯一数字的出现次数。

这是一个示例:

import numpy as np

a = np.array([[2, 2, 3, 3],
              [2, 3, 3, 3],
              [3, 3, 4, 4]])

结果应该是

[[2, 1, 0, 0],
 [1, 2, 2, 2],
 [0, 0, 1, 1]])

例如,第一行是每列中数字 2 的出现次数,0 表示 2 不在第三和第四列中。第二行是数字 3 的出现次数,而最后一行是数字 4 的出现次数。
简而言之,我想获取每个排序唯一值的每列计数。

我尝试过 np.unique(a, return_counts=True, axis=0),但得到了错误的结果:

(array([[2, 2, 3, 3],
        [2, 3, 3, 3],
        [3, 3, 4, 4]]),
 array([1, 1, 1]))
英文:

I have a 2d array and want to get the occurrences of all unique numbers by column.

Here's an example:

import numpy as np

a = np.array([[2,2,3,3],
              [2,3,3,3],
              [3,3,4,4]])

The result should be

[[2,1,0,0],
 [1,2,2,2],
 [0,0,1,1]])

For example, the first row is the occurrence of number 2 in each column, 0 means 2 isn't in the third and fourth columns. The second row is the occurrence of the number 3 while the last row is for the number 4.
Briefly, I wanna get the per-column count of each sorted unique value.

I have tried np.unique(a, return_counts=True, axis=0), but got this wrong result:

(array([[2, 2, 3, 3],
        [2, 3, 3, 3],
        [3, 3, 4, 4]]),
 array([1, 1, 1]))

答案1

得分: 5

你可以在数组上使用 np.unique 函数来获取整个矩阵中不同值的列表。然后将这些唯一值与原始矩阵进行广播比较,并对匹配项进行求和:

import numpy as np

a = np.array([[2,2,3,3],
              [2,3,3,3],
              [3,3,4,4]])

(np.unique(a)[:,None,None]==a).sum(axis=1)

[[2 1 0 0]
 [1 2 2 2]
 [0 0 1 1]]
英文:

You can use np.unique on the array to obtain the list of distinct values across the entire matrix. Then compare the unique values with the original matrix in a broadcast and sum up the matches:

import numpy as np

a = np.array([[2,2,3,3],
              [2,3,3,3],
              [3,3,4,4]])

(np.unique(a)[:,None,None]==a).sum(axis=1)

[[2 1 0 0]
 [1 2 2 2]
 [0 0 1 1]]

huangapple
  • 本文由 发表于 2023年7月11日 02:38:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定