使用NumPy计算二维数组理论值出错,求问题原因与修正方案
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

