Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a function that takes in a variable that would work if it is any of the following three types

 1. pandas Series  2. numpy array (ndarray)  3. python list 

Any other type should be rejected. What is the most efficient way to check this?

like image 537
Zhang18 Avatar asked May 02 '17 23:05

Zhang18


People also ask

How do you check if a variable is in an array Python?

To check if an array contains an element or not in Python, use the in operator. The in operator checks whether a specified element is an integral element of a sequence like string, array, list, tuple, etc.

Is a pandas series the same as a NumPy array?

The essential difference is the presence of the index: while the Numpy Array has an implicitly defined integer index used to access the values, the Pandas Series has an explicitly defined index associated with the values.

How do you check if a value is in a NumPy array?

Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the “in” operator. “in” operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values 'True” and “False“.


2 Answers

You can do it using isinstance:

import pandas as pd import numpy as np def 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.

like image 133
Miriam Farber Avatar answered Sep 23 '22 10:09

Miriam Farber


Python type() should do the job here

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

When you print

type(l) list  type(s) pandas.core.series.Series  type(arr) numpy.ndarray 
like image 24
Vaishali Avatar answered Sep 22 '22 10:09

Vaishali