Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a python object is a numpy ndarray

I have a function that takes an array as input and does some computation on it. The input array may or may not be a numpy ndarray (may be a list, pandas object, etc).

In the function, I convert the input array (regardless of its type) to a numpy ndarray. But this step may be computationally expensive for large arrays, especially if the function is called multiple times in a for loop.

Hence, I want to convert the input array to numpy ndarray ONLY if it is not already a numpy ndarray.

How can I do this?

import numpy as np

def myfunc(array):
    # Check if array is not already numpy ndarray
    # Not correct way, this is where I need help
    if type(array) != 'numpy.ndarray':
        array = np.array(array)

    # The computation on array
    # Do something with array
    new_array = other_func(array)
    return new_array
like image 227
JafetGado Avatar asked Mar 05 '20 17:03

JafetGado


3 Answers

You're quite close, but you need to call the specific class, i.e numpy.ndarray (here you're just comparing with a string). Also for this you have the built-in isinstance, too see if a given object is an instance of another:

def myfunc(array):
    # Check if array is not already numpy ndarray
    if not isinstance(array, np.ndarray):
        array = np.array(array)

    # The computation on array
    # Do something with array
    new_array = other_func(array)
    return new_array
like image 167
yatu Avatar answered Nov 14 '22 21:11

yatu


You can use isinstance here.

import numpy as np
a=np.array([1,2,...])
isinstance(a,np.ndarray)
#True

def myfunc(array):
    return array if isinstance(array,np.ndarray) else np.array(array)

You just return array if it's a np.ndarray already else you convert array to np.array.

like image 22
Ch3steR Avatar answered Nov 14 '22 23:11

Ch3steR


It is simpler to use asarray:

def myfunc(arr):
    arr = np.asarray(arr)
    # The computation on array
    # Do something with array
    new_array = other_func(arr)
    return new_array

If arr is already an array, asarray does not make a copy, so there's no penalty to passing it through asarray. Let numpy do the testing for you.

numpy functions often pass their inputs through asarray (or variant) just make sure the type is what they expect.

like image 21
hpaulj Avatar answered Nov 14 '22 23:11

hpaulj