How to gather all the values that repeated the most in each row of the numpy array, like the result of np.unique.
However, I want to avoid loops as the data to be handle will be much larger (much more rows).

请参见下面的示例

Input: a is a 2D array, had the shape of (x, k), where x would be very large.
a = np.asarray([[2, 7, 7, 2, 1], [1, 2, 3, 5, 5], [6, 6, 6, 6, 6]])

理想输出:[[2,7], [5], [6]]个,第一行有[2,7]个,两次都存在

使用循环几乎可以完成这项工作,但np.unique似乎不适用于多维数组

[np.array(np.unique(i, return_counts=1)) for i in a]

# decent output
> [array([[1, 2, 7],[1, 2, 2]], dtype=int64), 
   array([[1, 2, 3, 5], [1, 1, 1, 2]], dtype=int64),
   array([[6], [5]], dtype=int64)]


# Multi-dimension Input
np.unique(a, return_counts=1, axis=1)

# Useless Output
> (array([[1, 2, 2, 7, 7],
        [5, 1, 5, 2, 3],
        [6, 6, 6, 6, 6]]),
 array([1, 1, 1, 1, 1], dtype=int64))

推荐答案

使用statistics.multimode:

from statistics import multimode

out = list(map(multimode, a))

输出:

[[2, 7], [5], [6]]

Python相关问答推荐

我在使用fill_between()将最大和最小带应用到我的图表中时遇到问题

如何检测背景有噪的图像中的正方形

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

Mistral模型为不同的输入文本生成相同的嵌入

如何合并两个列表,并获得每个索引值最高的列表名称?

通过ManyToMany字段与Through在Django Admin中过滤

使用Python从rotowire中抓取MLB每日阵容

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

以逻辑方式获取自己的pyproject.toml依赖项

如何在Python Pandas中填充外部连接后的列中填充DDL值

在numpy数组中寻找楼梯状 struct

如何根据rame中的列值分别分组值

如何提高Pandas DataFrame中随机列 Select 和分配的效率?

用0填充没有覆盖范围的垃圾箱

一维不匹配两个数组上的广义ufunc

多索引数据帧到标准索引DF

如何在PYTHON中向单元测试S Side_Effect发送额外参数?

Pandas ,快速从词典栏中提取信息到新栏

如何在微调Whisper模型时更改数据集?

PyTorch变压器编码器中的填充掩码问题