What does (slice (None),None) mean in Python?
-
I was reading some numpy codes when I found this: tup = (slice(None),None) X -= X.mean(1) [tup] where X is a numpy array. Could anyone explain this line of code? Especially what the (slice(None), None) part? The python documentation has explanation of what slice() does, but I was unable to find what slice(None) means.
-
Answer:
All the answers are correct but what's confusing might be how tup=(slice(None), None) translates to the "standard" way of indexing. Basically the code in the question is equivalent to X -= X.mean(axis=1)[::, None] which is also equivalent to X -= X.mean(axis=1)[::, np.newaxis] So slice(None) is adding "::", and the None as the last element in tup is adding a new axis, to transpose the result of mean(axis=1).
Taro Sato at Quora Visit the source
Other answers
slice(None) creates a slice instance as slice(None, None, None) with default for start, step and end (see [1]). Wrt your code snippet, the tuple returns the individual computed means on the second axis as per [2]. Let's confirm this: >>> import numpy as np >>> arr = np.array([[1, 2], [3, 4]]) >>> arr.mean(1)[(slice(None), None)] array([[ 1.5], [ 3.5]]) >>> arr -= arr.mean(1)[(slice(None), None)] >>> arr array([[0, 0], [0, 0]]) [1] http://docs.python.org/2/library/functions.html#slice [2] http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html
Anuj Bhatt
slice() creates an instance of type slice. A slice instance I can be used to index a sequence S in an expression of the form S[I]. Here is the general form: slice(start, limit, step) The result is a slice that is equivalent to start:limit:step. Use None to get the default value for any of the three arguments. that code set up a tuple with (start:limit:step, None)
Paolo Gambardella
Related Q & A:
- What exactly does the asterisk (*) mean in WPF?Best solution by excelforum.com
- What does cogito ergo sum mean in latin?Best solution by en.wikipedia.org
- What does the word psych mean to you?Best solution by Yahoo! Answers
- What does "money on deposit" mean?Best solution by Yahoo! Answers
- What does unsigned in mysql mean?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.