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

如何统计Numpy数组中指定元素集合的出现次数?

统计Numpy数组中包含指定元素集合的行数

首先定义你的Numpy数组:

import numpy as np

arr = np.array([[1, 2, 3],
                [1, 2, 5],
                [3, 4, 6],
                [2, 5, 4],
                [5, 4, 3],
                [3, 5, 1],
                [2, 5, 1]])

高效的向量化实现方案

使用Numpy的向量化操作完成统计,避免逐行遍历的低效问题:

def count_set(target_elements):
    # 为每个目标元素生成「该行是否包含该元素」的布尔数组
    element_masks = [np.isin(arr, elem).any(axis=1) for elem in target_elements]
    # 合并所有mask:只有当所有目标元素都在该行出现时,结果为True
    combined_mask = np.logical_and.reduce(element_masks)
    # 统计符合条件的行数
    return combined_mask.sum()

调用示例:

print(count_set([1, 2]))  # 输出:3

代码解释

  1. np.isin(arr, elem):生成与原数组形状一致的布尔数组,标记每个位置的元素是否等于elem;
  2. .any(axis=1):将每行的结果合并为单个布尔值——只要该行存在elem,就返回True;
  3. np.logical_and.reduce(element_masks):对所有目标元素的布尔数组做逻辑与操作,得到最终掩码:只有当该行包含所有目标元素时,掩码值为True;
  4. .sum():统计掩码中True的数量,即符合条件的行数。

备选方案(纯Python遍历,适合小数组)

如果数组规模较小,也可以用集合的子集判断实现:

def count_set_python(target_elements):
    target_set = set(target_elements)
    count = 0
    for row in arr:
        if target_set.issubset(set(row)):
            count += 1
    return count

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:32:22