I am trying to use numpy_where to find the index of a particular value. Though I have searched quite a bit on the web including stackoverflow I did not find a simple 1D example.
ar=[3,1,4,8,2,1,0]
>>> np.where(ar==8)
(array([], dtype=int64),)
I expected np.where(ar==8) to return me the index/location of 8 in the the array. What am I doing wrong? Is it something in my array? Thanks
You can't transpose a 1D array (it only has one dimension!), but you can do what you want. You can use build array to combine the 3 vectors into 1 2D array, and then use Transpose Array on the 2D array.
It returns a new numpy array, after filtering based on a condition, which is a numpy-like array of boolean values. For example, if condition is array([[True, True, False]]) , and our array is a = ndarray([[1, 2, 3]]) , on applying a condition to array ( a[:, condition] ), we will get the array ndarray([[1 2]]) .
Use reshape() Function to Transform 1d Array to 2d Array To modify the layout of a NumPy ndarray, we will be using the reshape() method. Any form transition is accessible, even switching from a one-dimensional into a two-dimensional array. The measurement of the dimension is immediately computed when we have to use -1.
This is a really good example of how the range of variable types in Python and numpy
can be confusing for a beginner. What's happening is [3,1,4,8,2,1,0]
returns a list, not an ndarray
. So, the expression ar == 8
returns a scalar False
, because all comparisons between list and scalar types return False
. Thus, np.where(False)
returns an empty array. The way to fix this is:
arr = np.array([3,1,4,8,2,1,0])
np.where(arr == 8)
This returns (array([3]),)
. There's opportunity for further confusion, because where
returns a tuple. If you write a script that intends to access the index position (3, in this case), you need np.where(arr == 8)[0]
to pull the first (and only) result out of the tuple. To actually get the value 3, you need np.where(arr == 8)[0][0]
(although this will raise an IndexError
if there are no 8's in the array).
This is an example where numeric-specialized languages like Matlab or Octave are simpler to use for newbies, because the language is less general and so has fewer return types to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With