3

I am using Numeric Python. Unfortunately, NumPy is not an option. If I have multiple arrays, such as:

a=Numeric.array(([1,2,3],[4,5,6],[7,8,9]))
b=Numeric.array(([9,8,7],[6,5,4],[3,2,1]))
c=Numeric.array(([5,9,1],[5,4,7],[5,2,3]))

How do I return an array that represents the element-wise median of arrays a,b and c?...such as,

array(([5,8,3],[5,5,6],[5,2,3]))

And then looking at a more general situation: Given n number of arrays, how do I find the percentiles of each element? For example, return an array that represents the 30th percentile of 10 arrays. Thank you very much for your help!

steelymatt
  • 39
  • 2

3 Answers3

1

Combine your stack of 2-D arrays into one 3-D array, d = Numeric.array([a, b, c]) and then sort on the third dimension. Afterwards, the successive 2-D planes will be rank order so you can extract planes for the low, high, quartiles, percentiles, or median.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • Would you be able to write this out for me? I'd really appreciate it. Thanks. – steelymatt Apr 01 '12 at 21:46
  • @steelymatt I know this is late but I wrote something similar out - [element-wise median of three 2-d arrays](http://stackoverflow.com/a/13753506/206192) - as an answer to another question. – John Lyon Dec 06 '12 at 22:30
0

Putting Raymond Hettinger's description into python:

a=Numeric.array(([1,2,3],[4,5,6],[7,8,9]))
b=Numeric.array(([9,8,7],[6,5,4],[3,2,1]))
c=Numeric.array(([5,9,1],[5,4,7],[5,2,3]))

d = Numeric.array([a, b, c])
d.sort(axis=0)

Since there are n=3 input matrii so the median would be that of the middle one, the one indexed by one,

print d[n//2]
[[5 8 3]
 [5 5 6]
 [5 2 3]]

And if you had 4 input matrii, you would have to get the mean-elements of d[1] and d[2].

0

Well, I'm not versed in Numeric, but I'll just start with a naive solution and see if we can make it any better.

To get the 30th percentile of list foo let x=0.3, sort the list, and pick the the element at foo[int(len(foo)*x)]

For your data, you want to put it in a matrix, transpose it, sort each row, and get the median of each row.

A matrix in Numeric (just like numpy) is an array with two dimensions.

I think that bar = Numeric.array(a,b,c) would make Array you want, and then you could get the nth column with 'bar[:,n]' if Numeric has the same slicing techniques as Numpy.

foo = sorted(bar[:,n])
foo[int(len(foo)*x)]

I hope that helps you.

Nathan
  • 6,095
  • 10
  • 45
  • 54