Rilcon42
Rilcon42

Reputation: 9763

Convert Dataframe column to resolve TypeError Cannot be hashed

This question has been asked many times on SO, but in every case I found the answer was always to change the OP's code to get the correct result a different way. Example Example

Rather than using a different method to solve the problem, how do you convert a dataframe column to something that can be hashed? Or, if that is not possible, why do you have to use another method?

import pandas as pd

d = {'name':['bil','bil','bil','jim'],
     'col2': ['acct','law', 'acct2','law'],
     'col3': [1,2,3,55],
     'col4': [1,1,1,2]

    }
df2 = pd.DataFrame(data=d)
coursesFilter=['acct']

print(df2[df2['col2'].isin([coursesFilter])]) #TypeError: unhashable type: 'list'
print(df2[df2['col2'].isin([pd.Series(coursesFilter)])]) #TypeError: 'Series' objects are mutable, thus they cannot be hashed
print(df2[df2['col2'].isin([pd.Series(coursesFilter).tolist()])]) #TypeError: unhashable type: 'list'

Upvotes: 1

Views: 538

Answers (2)

BENY
BENY

Reputation: 323266

Your coursesFilter already a list object , do not need add []

df2[df2['col2'].isin(coursesFilter)]
Out[410]: 
   col2  col3  col4 name
0  acct     1     1  bil

Upvotes: 1

jezrael
jezrael

Reputation: 862691

I think need remove []:

print(df2[df2['col2'].isin(coursesFilter)])
print(df2[df2['col2'].isin(pd.Series(coursesFilter))])
print(df2[df2['col2'].isin(pd.Series(coursesFilter).tolist())])

Input Series.isin parameters:

values : set or list-like

The sequence of values to test. Passing in a single string will raise a TypeError. Instead, turn a single string into a list of one element.

Upvotes: 2

Related Questions