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

计算二维numpy数组各列非零元素的平均值

Numpy二维数组按列统计非零值平均值实现方案

直接用numpy数组的基础聚合方法即可实现,不需要依赖矩阵专属接口,核心逻辑为按列分别计算总和、非零元素个数,两者相除即可得到结果。

完整代码示例

import numpy as np

# 构造示例数组
arr = np.array([
    [0, 0, 0, 0],
    [0, 2, 5, 0],
    [1, 5, 8, 1],
    [1, 5, 8, 2],
    [0, 2, 5, 0],
    [0, 0, 0, 0]
])

# 按列求和
col_total = arr.sum(axis=0)
# 统计每列非零元素数量
col_nonzero_cnt = (arr != 0).sum(axis=0)
# 计算非零平均值
avg_result = col_total / col_nonzero_cnt

print(avg_result)
# 输出:[0.5 3.5 6.5 1.5] 完全匹配预期的分数计算结果

如果需要保留分数形式输出,可以额外调用fractions模块处理:

from fractions import Fraction
frac_result = [Fraction(int(s), int(c)) for s, c in zip(col_total, col_nonzero_cnt)]
print(frac_result)
# 输出:[Fraction(1, 2), Fraction(7, 2), Fraction(13, 2), Fraction(3, 2)] 和给出的分数预期完全一致

注意事项

如果存在全零列,上述计算会触发除以零的警告,可根据业务需要加过滤逻辑,比如把全零列的结果置为0:

avg_result = np.where(col_nonzero_cnt == 0, 0, col_total / col_nonzero_cnt)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:45:03