Finding range of a numpy array elements

Question:

I have a NumPy array of size 94 x 155:

a = [1  2  20  68  210  290..
     2  33 34  55  230  340..
     .. .. ... ... .... .....]

I want to calculate the range of each row, so that I get 94 ranges in a result. I tried looking for a numpy.range function, which I don’t think exists. If this can be done through a loop, that’s also fine.

I’m looking for something like numpy.mean, which, if we set the axis parameter to 1, returns the mean for each row in the N-dimensional array.

Asked By: khan

||

Answers:

I think np.ptp might do what you want:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ptp.html

r = np.ptp(a,axis=1)

where r is your range array.

Answered By: JoshAdel

Try this:

def range_of_vals(x, axis=0):
    return np.max(x, axis=axis) - np.min(x, axis=axis)
Answered By: Austin Waters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.