Summarize by np.array or np.float

We have a numpy-based algorithm that should process data of various types.

def my_fancy_algo(a): b = np.sum(a, axis=1) # Do something b return b 

If we pass a=np.array[1.0, 2.0, 3.0] , then b will take the value [6.0] .

If we pass a=6.0 , then we get

 *** ValueError: 'axis' entry is out of bounds 

The desired behavior would be that we get the same return value 6.0 not ( [6.0] ) for both inputs.

What is the right pythonic and safe way to handle this? type ? shape ?

+5
source share
2 answers

Your array of examples actually gives the same problem as the scalar:

 >>> a = np.array([1.0,2.0,3.0]) >>> np.sum(a, axis=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/numpy/core/fromnumeric.py", line 1724, in sum out=out, keepdims=keepdims) File "/usr/lib/python3.4/site-packages/numpy/core/_methods.py", line 32, in _sum return umr_sum(a, axis, dtype, out, keepdims) ValueError: 'axis' entry is out of bounds 

The good news is that there is a numpy function just to ensure that numpy calls are made using axis=1 - this is called np.atleast_2d :

 >>> np.sum(np.atleast_2d(a), axis=1) array([ 6.]) >>> np.sum(np.atleast_2d(6.0), axis=1) array([ 6.]) 

But since you obviously want a scalar answer, instead you can simply completely reject the axis argument:

 >>> np.sum(a) 6.0 >>> np.sum(6.0) 6.0 
+9
source

np.sum(np.array([1.0, 2.0, 3.0]), axis=1) produces a ValueError: 'axis' entry is out of bounds for me.

Did you want to put axis=0 on line 2? Then it works with both arrays and scalars:

 >>> np.sum(np.array([1.0, 2.0, 3.0]), axis=0) 6 >>> np.sum(3, axis=0) 3 
+3
source

All Articles