I am experimenting with the numpy.where(condition[, x, y])
function.
From the numpy documentation, I learn that if you give just one array as input, it should return the indices where the array is non-zero (i.e. "True"):
If only condition is given, return the tuple condition.nonzero(), the indices where condition is True.
But if try it, it returns me a tuple of two elements, where the first is the wanted list of indices, and the second is a null element:
>>> import numpy as np
>>> array = np.array([1,2,3,4,5,6,7,8,9])
>>> np.where(array>4)
(array([4, 5, 6, 7, 8]),) # notice the comma before the last parenthesis
so the question is: why? what is the purpose of this behaviour? in what situation this is useful?
Indeed, to get the wanted list of indices I have to add the indexing, as in np.where(array>4)[0]
, which seems... "ugly".
ADDENDUM
I understand (from some answers) that it is actually a tuple of just one element. Still I don't understand why to give the output in this way. To illustrate how this is not ideal, consider the following error (which motivated my question in the first place):
>>> import numpy as np
>>> array = np.array([1,2,3,4,5,6,7,8,9])
>>> pippo = np.where(array>4)
>>> pippo + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "int") to tuple
so that you need to do some indexing to access the actual array of indices:
>>> pippo[0] + 1
array([5, 6, 7, 8, 9])