Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error, 'only list-like objects are allowed to be passed to isin(), you passed a [int]'

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'])

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:

df[df.reports.isin(24)]

The error comes as: only list-like objects are allowed to be passed to isin(), you passed a [int].

Also, how can i find the corresponding 'name' against reports 24, (i.e., Molly)

like image 770
John Avatar asked Aug 15 '17 18:08

John


1 Answers

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 could use .isin with a single-element list:

>>> 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 large data-frame (over 10,000 rows, let's say) and a more complex boolean-expression, you can do this efficiently with 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.

like image 135
juanpa.arrivillaga Avatar answered Oct 16 '22 20:10

juanpa.arrivillaga