Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Should I use newaxis or None?

Tags:

python

numpy

In numpy one can use the 'newaxis' object in the slicing syntax to create an axis of length one, e.g.:

import numpy as np print np.zeros((3,5))[:,np.newaxis,:].shape # shape will be (3,1,5) 

The documentation states that one can also use None instead of newaxis, the effect is exactly the same.

Is there any reason to choose one over the other? Is there any general preference or style guide? My impression is that newaxis is more popular, probably because it is more explicit. So is there any reason why None is allowed?

like image 315
nikow Avatar asked Jun 03 '09 13:06

nikow


People also ask

Why do we use NP Newaxis?

Simply put, numpy. newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus, 1D array will become 2D array.

What does .all do in Numpy?

all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.

How do you add an axis in Python?

Method 1: Using numpy.newaxis() newaxis object. This object is equivalent to use None as a parameter while declaring the array. The trick is to use the numpy. newaxis object as a parameter at the index location in which you want to add the new axis.


1 Answers

None is allowed because numpy.newaxis is merely an alias for None.

In [1]: import numpy  In [2]: numpy.newaxis is None Out[2]: True 

The authors probably chose it because they needed a convenient constant, and None was available.

As for why you should prefer newaxis over None: mainly it's because it's more explicit, and partly because someday the numpy authors might change it to something other than None. (They're not planning to, and probably won't, but there's no good reason to prefer None.)

like image 105
AFoglia Avatar answered Oct 10 '22 01:10

AFoglia