如何检查变量是python列表、numpy数组还是pandas系列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43748991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a variable is either a python list, numpy array or pandas series
提问by Zhang18
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?
应拒绝任何其他类型。检查这个的最有效方法是什么?
回答by Miriam Farber
You can do it using isinstance
:
您可以使用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.
然后f([1,2,3])
打印 5 并f(3.34)
引发错误。
回答by Vaishali
Python type() should do the job here
Python type() 应该在这里完成工作
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
回答by SethMMorton
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.
这一切都取决于您要实现的目标(您是否允许使用元组,range
对象怎么样?),但限制要少一些,但仍然不允许使用字符串(我猜这就是您真正想要实现的目标)您可以使用以下代码。
import collections
import pandas
import numpy
def 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!!!!!
回答by shreesh katti
You can use isinstance like this:
您可以像这样使用 isinstance:
import pandas as pd
import numpy as np
#Simple List
simple_list = [1,2]
#numpy array
np_array = np.array(simple_list)
#Pandas series
pandas_series = pd.Series(simple_list)
if isinstance(simple_list, list):
print("This is a list: ", simple_list)
if isinstance(np_array, np.ndarray):
print("This is a numpy array: ", np_array)
if isinstance(pandas_series, pd.core.series.Series):
print("This is pandas series: ", pandas_series)