Search code examples
python-2.7numpymedian

Getting median of a multidemensional array of differing lengths


Given my array

x = numpy.array([[1.0,2.0,3.0],[10.0,20.0,30.0]])

I could get the median of each element easily with

np.median(x, axis=0)

#output: array([  2.,  20.])

But I cannot do the same thing when I increase the length of one array

x = numpy.array([[1.0,2.0,3.0],[10.0,20.0,30.0, 40.0]])

output should be array([ 2., 25.])

Is there a way to still get the median for such an array?


Solution

  • [np.median(i) for i in x]
    

    Since the list's have unequal length you can't broadcast them. That's why the first work, but not the second.

    In the fist case, your two list's will get broadcast into a 3x2 array where a median along a axis makes sense. Now the two list's of unequal length can't be broadcast this way.