pandas 错误,“只允许将类似列表的对象传递给 isin(),您传递了一个 [int]”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45699651/
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
Error, 'only list-like objects are allowed to be passed to isin(), you passed a [int]'
提问by John
Following adopted code is just used for example purposes:
以下采用的代码仅用于示例目的:
data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'year': [2012, 2012, 2013, 2014, 2014],
'reports': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
value_list = ['Tina', 'Molly', 'Jason']
value_list = ['Tina', 'Molly', 'Jason']
df[df.name.isin(value_list)]
Here, it can be seen that a list (i.e., value_list) has been passed. If i don't want to pass a list and just want to pass an integer (i.e, 24 in the reports column to find its corresponding row), what would be the ideal way. I tried to do this, but it actually doesn't works:
到这里,可以看出传入了一个列表(即value_list)。如果我不想传递列表而只想传递一个整数(即,报告列中的 24 以找到其对应的行),那么理想的方法是什么。我试图这样做,但它实际上不起作用:
df[df.reports.isin(24)]
The error comes as: only list-like objects are allowed to be passed to isin(), you passed a [int].
错误是:只允许将类似列表的对象传递给 isin(),您传递了一个 [int]。
Also, how can i find the corresponding 'name' against reports 24, (i.e., Molly)
另外,我如何才能根据报告 24(即 Molly)找到相应的“姓名”
采纳答案by juanpa.arrivillaga
Just use boolean-indexing:
只需使用布尔索引:
>>> df
name reports year
Cochice Jason 4 2012
Pima Molly 24 2012
Santa Cruz Tina 31 2013
Maricopa Jake 2 2014
Yuma Amy 3 2014
>>> df[df.reports == 24]
name reports year
Pima Molly 24 2012
You coulduse .isin
with a single-element list:
您可以使用.isin
单元素列表:
>>> df[df.reports.isin([24])]
name reports year
Pima Molly 24 2012
But the boolean-indexing option is what you would typically see.
但是布尔索引选项是您通常会看到的。
If you have a largedata-frame (over 10,000 rows, let's say) and a more complex boolean-expression, you can do this efficiently with df.query
:
如果您有一个大型数据框(比方说超过 10,000 行)和一个更复杂的布尔表达式,您可以使用以下命令有效地执行此操作df.query
:
>>> df.query("reports==24 or name == 'Jason'")
name reports year
Cochice Jason 4 2012
Pima Molly 24 2012
And this will be fast and memory-efficient if you have the numexpr
engine available.
如果您有numexpr
可用的引擎,这将是快速且节省内存的。