Bakes
Bakes

Reputation: 71

Pandas error with multidimensional key using .loc and a boolean

Been running into this same error for 2 weeks, even though the code worked before. Not sure if I updated pandas as part of another library install, and maybe something changed there. Currently on version 23.4. Expected outcome is returning just the row with that identifier value.

In [42]: df.head()

Out[43]:

index   Identifier  ... 
0        51384710   ... 
1        74838J10   ... 
2        80589M10   ...     
3        67104410   ... 
4        50241310   ... 

[5 rows x 14 columns]
In [43]: df.loc[df.Identifier.isin(['51384710'])].head()
    Traceback (most recent call last):
      File "C:\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-44-a3dbf43451ef>", line 1, in <module>
     df.loc[df.Identifier.isin(['51384710'])].head()
File "C:\anaconda3\lib\site-packages\pandas\core\indexing.py", line 1478, in __getitem__
        return self._getitem_axis(maybe_callable, axis=axis)
File "C:\anaconda3\lib\site-packages\pandas\core\indexing.py", line 1899, in _getitem_axis
        raise ValueError('Cannot index with multidimensional key')
    **ValueError: Cannot index with multidimensional key**

Code Snippet

Upvotes: 2

Views: 11496

Answers (2)

Bakes
Bakes

Reputation: 71

Fixed it. I'd done df.columns = [column_list] where column_list = [...], which caused df to be treated as if it had a multiindex, even though there was only one level. removed the brackets from the df.columns assignment.

Upvotes: 5

Peter Leimbigler
Peter Leimbigler

Reputation: 11105

Try changing

df.loc[df.Identifier.isin(['51384710'])].head()

to

df[df.Identifier.isin(['51384710'])].head()

Upvotes: -1

Related Questions