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.
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.
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
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
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.