Search code examples
pythonnumpysubset

Avoiding DeprecationWarning when extracting indices to subset vectors


General idea: I want to take a slice of a 3D surface plot of a function of two variables f(x,y) at a given x = some value. The problem is that I have to know the index where x assumes this value after creating x as a vector with np.linspace, for instance. Finding this index turns out to be doable thanks to another post in SO. What I can't do is use this index as is returned to subset a different vector Z, because of the index is returned as a 1-element list (or tuple), and I need an integer. When I use int() I get a warning:

import numpy as np

lim = 10
x = np.linspace(-lim,lim,2000)
y = np.linspace(-lim,lim,2000)

X, Y = np.meshgrid(x, y)

Z = X**2 + Y**2

def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]

idx = int(np.where(x == find_nearest(x,0))[0])
print(idx)
print(Z[idx,:].shape)

Output with warning:

<ipython-input-282-c2403341abda>:16: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.)
  idx = int(np.where(x == find_nearest(x,0))[0])
1000
(2000,)

The shape of the ultimate sub-setting of Z is (2000,), which allows me to plot it against x.

However, if instead I just extract with [0] the value return by np.where(), the shape of the final sub-set Z, i.e. (1,2000) is not going to allow me to plot it against x:

idx1 = np.where(x == find_nearest(x,0))[0]
print(idx1)
print(Z[idx1,:].shape)

How can I extract the index corresponding to the value of x is want as an integer, and thus avoid the warning (see below)?

DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) idx = int(np.where(x == find_nearest(x,0))[0])


Solution

  • Break down the resulting value you get from np.where:

    >>> np.where(x == find_nearest(x,0))
    (array([1000]),)
    

    Then dereference the first element:

    >>> np.where(x == find_nearest(x,0))[0]
    array([1000])
    

    Ok, same thing. Get first element:

    >>> np.where(x == find_nearest(x,0))[0][0]
    1000