You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计numpy二维数组中各子数组的出现次数

numpy二维数组统计子数组出现次数实现方法

你可以通过以下两种常用方案实现需求,两种方案都可以直接关联子数组和对应计数:

方案1:使用numpy原生API实现(性能最优,适合大数据量场景)

numpy 1.13及以上版本支持np.unique的axis参数,直接按行统计唯一值及对应计数:

import numpy as np

samples = np.array([[1,2,3], [2,3,4], [4,5,6], [1,2,3], [2,3,4], [2,3,4]])
# 按行获取唯一子数组和对应计数
unique_subarr, counts = np.unique(samples, axis=0, return_counts=True)

# 如需转成键值对关联结构,将子数组转成元组(列表不可作为字典键)
result = {tuple(row): cnt for row, cnt in zip(unique_subarr, counts)}

输出的result结果为:{(1, 2, 3): 2, (2, 3, 4): 3, (4, 5, 6): 1},和你期望的结构完全一致。unique_subarr和counts的下标一一对应,需要直接使用numpy格式子数组时直接按下标取即可。

方案2:使用Python标准库collections.Counter实现(不依赖numpy版本)

如果不想依赖高版本numpy的API,可以用Python自带的Counter工具实现:

from collections import Counter
import numpy as np

samples = np.array([[1,2,3], [2,3,4], [4,5,6], [1,2,3], [2,3,4], [2,3,4]])
result = Counter(tuple(row) for row in samples)

输出结果和方案1完全一致。


内容的提问来源于stack exchange,提问作者Geena Ildefonso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:24:04