Ender
Ender

Reputation: 71

How to filter a dataframe with dictionary

Suppose I have a dataframe and a dictionary like this:

df = pd.DataFrame({"letters": ["a","b","c","b","c"], "numbers": [1,2,3,1,2]})
correct_mapping={"a":1,"b":2,"c":3}

I want to filter the rows which do not have the correct mapping.

I tried this, but it breaks:

df[correct_mapping[df["letters"]] != df["numbers"]]
TypeError: 'Series' objects are mutable, thus they cannot be hashed

Any help would be appreciated.

Expected output:

  letters  numbers
3       b        1
4       c        2

Upvotes: 2

Views: 49

Answers (1)

cs95
cs95

Reputation: 402443

Compare with map:

df[df['letters'].map(correct_mapping) != df['numbers']]                                                                                   
  letters  numbers
3       b        1
4       c        2

Upvotes: 2

Related Questions