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

Time:12-16

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?

CodePudding user response:

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.

  • Related