19

I'm trying to build a code that checks whether a given object is an np.array() in python.

if isinstance(obj,np.array()) doesn't seem to work.

I would truly appreciate any help.

2
  • 4
    np.ndarray, not np.array(): stackoverflow.com/a/36783987/483620 Commented Dec 11, 2019 at 6:17
  • Want to be mindful of subclasses too. Commented Dec 11, 2019 at 6:23

4 Answers 4

32

isinstance(obj, numpy.ndarray) may work

Sign up to request clarification or add additional context in comments.

Comments

10

You could compare the type of the object being passed to the checking function with 'np.ndarray' to check if the given object is indeed an np.ndarray

The sample code snippet for the same should look something like this :

if isinstance(obj,np.ndarray):
    # proceed -> is an np array
else
    # Not an np.ndarray

1 Comment

isinstance is the proper check in almost every case. This code will fail if value is an instance of a subclass of numpy.ndarray.
3

Below code seems to work. Use numpy.ndarray.

import numpy as np

l = [1,2,3,4]

l_arr = np.array(l)

if isinstance(l_arr, np.ndarray):
    print("Type is np.array")
else:
    print("Type is not np.array")

Output:

Type is np.array

Comments

2

The type of what numpy.array returns is numpy.ndarray. You can determine that in the repl by calling type(numpy.array([])). Note that this trick works even for things where the raw class is not publicly accessible. It's generally better to use the direct reference, but storing the return from type(someobj) for later comparison does have its place.

1 Comment

this is the simplest answer +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.