8

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.

Sam
  • 315
  • 1
  • 3
  • 14

4 Answers4

16

isinstance(obj, numpy.ndarray) may work

Kani
  • 1,072
  • 2
  • 7
  • 16
4

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
Alen S Thomas
  • 923
  • 7
  • 10
2

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
Jay
  • 24,173
  • 25
  • 93
  • 141
0

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.

Perkins
  • 2,409
  • 25
  • 23