计算数组中唯一数组的出现次数

2024-04-24 21:11:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由各种热编码的numpy数组组成的numpy数组,例如

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

我想数一数每一个独特的热载体的出现

^{pr2}$

Tags: numpy编码np数组arraypr2热载体
3条回答

给定数据格式的最快方法是:

x.sum(axis=0)

它给出了:

^{pr2}$

其中,第一个结果是第一个结果是热的数组的计数:

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

这利用了一个事实,一次只能有一个,所以我们可以分解直接和。在

如果您绝对需要将其扩展为相同的格式,可以通过以下方式进行转换:

sums = x.sum(axis=0)
{tuple(int(k == i) for k in range(len(sums))): e for i, e in enumerate(sums)}

或者,类似于塔拉希普卡:

{tuple(row): count for row, count in zip(np.eye(len(sums), dtype=np.int64), sums)}

产量:

{(1, 0, 0): 2, (0, 1, 0): 0, (0, 0, 1): 1}

方法1

似乎是使用^{}(v1.13及更高版本)的新功能的完美设置,它让我们可以沿着NumPy数组的轴工作-

unq_rows, count = np.unique(x,axis=0, return_counts=1)
out = {tuple(i):j for i,j in zip(unq_rows,count)}

样本输出-

^{pr2}$

方法2

对于大于v1.13的NumPy版本,我们可以利用这样一个事实:输入数组是一个热编码数组,如下-

_, idx, count = np.unique(x.argmax(1), return_counts=1, return_index=1)
out = {tuple(i):j for i,j in zip(x[idx],count)} # x[idx] is unq_rows

您可以将数组转换为元组并使用^{}

import numpy as np
from collections import Counter
x = np.array([[1, 0, 0], [0, 0, 1], [1, 0, 0]])
Counter([tuple(a) for a in x])
# Counter({(1, 0, 0): 2, (0, 0, 1): 1})

相关问题 更多 >