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

使用NumPy计算二维数组理论值出错,求问题原因与修正方案

Fixing NumPy Median to Return Column-Wise Values

Hey there! Let's figure out why your code isn't giving you the expected array of medians.

The Problem with Your Current Code

When you run np.median(arr) without specifying the axis parameter, NumPy defaults to computing the median of the entire flattened array. For your arr, that's the median of all 9 elements combined (sorted: [1,1,3,4,5,7,7,8,9]), which is 5 (you might have miscalculated the 4.67 part—maybe a typo or confusion with mean?). That's why you're getting a single scalar value instead of the column-wise median array you want.

The Fix: Specify the axis Parameter

NumPy's median function absolutely can return an array of medians—you just need to tell it which dimension to compute along. Since you want the median for each column (resulting in [5,3,7]), set axis=0:

import numpy as np
arr = [[1,3,4],[5,7,9],[8,1,7]]
theory = np.median(arr, axis=0)
print(theory)  # Output: [5. 3. 7.]

A Quick Breakdown of axis

  • axis=0: Computes the median column-wise (collapses rows, keeps columns)
  • axis=1: Computes the median row-wise (collapses columns, keeps rows) — for your array, this would give [3., 7., 7.]

That's all there is to it! By specifying axis=0, you're telling NumPy to calculate the median for each vertical column, which gives you exactly the target array you're after.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:20:58