How to check if a variable is either a python list, numpy array or pandas series How to check if a variable is either a python list, numpy array or pandas series arrays arrays

How to check if a variable is either a python list, numpy array or pandas series


You can do it using isinstance:

import pandas as pdimport numpy as npdef f(l):    if isinstance(l,(list,pd.core.series.Series,np.ndarray)):        print(5)    else:        raise Exception('wrong type')

Then f([1,2,3]) prints 5 while f(3.34) raises an error.


Python type() should do the job here

l = [1,2]s= pd.Series(l)arr = np.array(l) 

When you print

type(l)listtype(s)pandas.core.series.Seriestype(arr)numpy.ndarray


This all really depends on what you are trying to achieve (will you allow a tuple, how about a range object?), but to be a bit less restrictive but still disallow strings (which I am guessing is what you are really trying to achieve) you can use the following code.

import collectionsimport pandasimport numpydef myfunc(x):    if not isinstance(x, collections.abc.Iterable) or isinstance(x, (str, bytes)):        raise ValueError('A non-string iterable is required')    return 'Yay!'myfunc([9, 7])myfunc((9, 7))myfunc(numpy.arange(9))myfunc(range(9))myfunc(pandas.Series([9, 7]))myfunc('Boo')  # THIS WILL RAISE A ValueError!!!!!