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

17,443

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.

Share:
17,443
John
Author by

John

Updated on June 18, 2022

Comments

  • John
    John almost 2 years

    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)