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?
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.
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.
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“.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With