英文:
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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论