access to a dictionary value by passing a value from a pandas dataframe as dictionary key

Question:

There is a pandas df and a dictionary that its keys have gotten from this df. for example:

data = {'Type': [1, 1, 2, 3, 2] ,
    'Vol' : [10, 20, 15, 15, 15] ,
    'Cost' : [500, 300, 200, 250, 400] , 
    'IsSold' : [1, 1, 1, 1, 0]}

df = pd.DataFrame(data)

capacity = {key : 500 for key in df.Type.unique()}

A sub_dataframe will create with only one row of data:

sample_df = df.sample()

Now, I want to do this:

if sample_df['Cost'] <= capacity[sample_df['Type']] :
   #some procedure

But it returns an error when I run it:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

Can you help me with it?

Asked By: FZL

||

Answers:

Both LHS and RHS expressions are Pandas Series—not ‘a value from a pandas data frame’. One of the possible solutions, is to get the index of the Series that has been sampled, and use it to retrieve values:

index = sample_df.index[0]
sample_df['Cost'][index] <= capacity[sample_df['Type'][index]]

The error states that the object of type Series cannot be used as a key of a dictionary, because it’s mutable. Mutable objects in Python can’t be hashed and thus, can’t be used as dictionary keys.

Answered By: Lev Pleshkov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.