Creating ndarray from ragged nested sequences is deprecated

Borislav Hadzhiev

Last updated: Apr 10, 2024

Reading timeยท5 min

- Creating ndarray from ragged nested sequences is deprecated
- Set the
`dtype`

keyword argument to`object`

- Disabling the
`VisibleDeprecationWarning`

NumPy warning - Setting the
`action`

argument to`error`

The NumPy **"VisibleDeprecationWarning: Creating an ndarray from ragged nested
sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with
different lengths or shapes) is deprecated"** occurs when you create an array of
arrays where the subarrays are of different lengths.

To resolve the issue, set the `dtype`

keyword argument to `object`

or disable
the warning.

Here is the complete stack trace.

shell

`/home/borislav/Desktop/bobbyhadz_python/main.py:13: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.`

Here is an example of when the warning is shown.

main.py

`import numpy as np def get_arr(): arr = np.array([[1], [1, 2], [1, 2, 3]]) return arr # /home/borislav/Desktop/bobbyhadz_python/main.py:13: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray. get_arr()`

Notice that the subarrays that we passed to the numpy.array method are of different lengths.

A ragged (or jagged) array is an array of arrays (or a list of lists) where the subarrays have different lengths.

This produces rows of jagged edges when visualized as output.

`dtype`

keyword argument to `object`

Creating an `ndarray`

from ragged nested sequences is deprecated, however, you
can get around this by setting the `dtype`

keyword argument to `object`

.

main.py

`import numpy as np def get_arr(): arr = np.array([[1], [1, 2], [1, 2, 3]], dtype=object) return arr result = get_arr() # ๐๏ธ [list([1]) list([1, 2]) list([1, 2, 3])] print(result)`

The code for this article is available on GitHub

The `dtype`

(data type) keyword argument is optional and sets the data type for
the array.

If the argument is not supplied, then the type is determined as the minimum type required to hold the objects in the sequence.

If you have a ragged nested sequence that you need to convert to an `ndarray`

,
use the `asarray()`

method and set the `dtype`

keyword argument to `object`

.

main.py

`import numpy as np list_of_lists = [[1], [1, 2], [1, 2, 3]] arr = np.asarray(list_of_lists, dtype=object) # ๐๏ธ [list([1]) list([1, 2]) list([1, 2, 3])] print(arr)`

The numpy.asarray() method converts the supplied array-like value to an array.

The `dtype`

keyword argument is optional. If not set, the data type is inferred
from the input data.

`VisibleDeprecationWarning`

NumPy warningYou can also disable the `VisibleDeprecationWarning`

NumPy warning as an
alternative.

main.py

`import numpy as np np.warnings.filterwarnings( 'ignore', category=np.VisibleDeprecationWarning ) def get_arr(): arr = np.array([[1], [1, 2], [1, 2, 3]]) return arr result = get_arr() # ๐๏ธ [list([1]) list([1, 2]) list([1, 2, 3])] print(result)`

The code for this article is available on GitHub

If I run the code sample above, no warnings are raised, even though the `dtype`

keyword argument is not set to `object`

.

When the first argument of the `filterwarnings()`

method is set to `ignore`

,
matching warnings are never printed.

The `category`

keyword argument must be set to a class (a subclass of `Warning`

)
and specifies which warning category we want to match.

The approach only silences warnings of type `VisibleDeprecationWarning`

, so all
other NumPy warnings will still be printed.

`action`

argument to `error`

If you aren't sure where the warning is raised and you're trying to debug your
code, try to set the `action`

argument to `error`

.

main.py

`import numpy as np np.warnings.filterwarnings( 'error', category=np.VisibleDeprecationWarning ) def get_arr(): arr = np.array([[1], [1, 2], [1, 2, 3]]) return arr result = get_arr()`

The code for this article is available on GitHub

Notice that the `action`

argument is set to `error`

this time.

Running the code above produces the following output.

shell

`Traceback (most recent call last): File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 16, in <module> result = get_arr() File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 11, in get_arr arr = np.array([[1], [1, 2], [1, 2, 3]]) numpy.VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.`

As shown in the code sample, the error occurred on line 11.

main.py

`arr = np.array([[1], [1, 2], [1, 2, 3]])`

And the function call that triggered the error was on line 16.

main.py

`result = get_arr()`

This can help you to track down where the warning is raised.

You can learn more about the related topics by checking out the following tutorials:

- How to Convert JSON NULL values to None using Python
- How to convert a Tuple to JSON in Python
- How to Delete a JSON object from a List in Python
- ValueError: malformed node or string in Python [Solved]
- TypeError Invalid comparison between datetime64[ns] and date
- Could not broadcast input array from shape into shape [Fix]
- ValueError: object too deep for desired array [Solved]
- ValueError: cannot reindex on an axis with duplicate labels
- ValueError: Length mismatch: Expected axis has X elements, new values have Y elements
- ValueError: zero-dimensional arrays cannot be concatenated
- ValueError: all the input array dimensions for the concatenation axis must match exactly
- ValueError: cannot reshape array of size X into shape Y
- lbfgs failed to converge (status=1): STOP: TOTAL NO. of ITERATIONS REACHED LIMIT
- How to draw empty circles on a Scatter Plot in Matplotlib
- TypeError: Image data cannot be converted to float [Solved]
- OverflowError: Python int too large to convert to C long
- TypeError: Field elements must be 2- or 3-tuples, got 1
- ValueError: Expected 2D array, got 1D array instead [Fixed]
- TypeError: ufunc 'isnan' not supported for the input types
- Convert a Row to a Column Header in a Pandas DataFrame
- Arrays used as indices must be of integer (or boolean) type
- Get the column names of a NumPy ndarray in Python
- ValueError: No axis named X for object type DataFrame
- Calculate the average (mean) of 2 NumPy arrays
- NumPy or Pandas: How to check a Value or an Array for NaT
- Pandas: Changing the column type to Categorical
- How to flatten only some Dimensions of a NumPy array
- How to iterate over the Columns of a NumPy Array
- Pandas: Find an element's Index in Series [7 Ways]
- numpy.linalg.LinAlgError: Singular matrix [Solved]
- NumPy: Unable to allocate array with shape and data type
- NumPy RuntimeWarning: invalid value encountered in divide
- All the input arrays must have same number of dimensions
- Only integer scalar arrays can be converted to a scalar index
- ValueError: Index contains duplicate entries, cannot reshape