Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

python - Numpy: Should I use newaxis or None?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...