Nikita Tsekhanovich
Nikita Tsekhanovich

Reputation: 129

How to wright a function to work with dictionary type Serires and a column in Dataframe?

I am trying to wright a function that works with Series and Dataframe.

dct= {10: 0.5, 20: 2, 30: 3,40:4}
#Defining the function
def funtion_dict(row,dict1):
    total_area=row['total_area']
    if total_area.round(-1) in dict1:     
        return dict1.get(total_area.round(-1))*total_area

#checking function in a test situation
row = pd.DataFrame(
    {
        'total_area': [53, 14.8, 94, 77, 12],
        'b': [5, 4, 3, 2, 1],
        'c': ['X', 'Y', 'Y', 'Y', 'Z'],
    }
)

print(funtion_dict(row,dct))

I keep getting an error 'Series' objects are mutable, thus they cannot be hashed'. Please help

Upvotes: 1

Views: 45

Answers (1)

Jerven Clark
Jerven Clark

Reputation: 1219

This is the expected behavior because you are trying to use a "Series" as a lookup for a dictionary which is not allowed.

From your code,

dct= {10: 0.5, 20: 2, 30: 3,40:4}
df = pd.DataFrame({
    'total_area': [53, 14.8, 94, 77, 12],
    'b': [5, 4, 3, 2, 1],
    'c': ['X', 'Y', 'Y', 'Y', 'Z'],
})

If you want to add another column to your data frame with multipliers matched from a dictionary, you can do it like so:

df['new_column'] = df['total_area'].round(-1).map(dct) * df['total_area']

which will then give you

   total_area  b  c  new_column
0        53.0  5  X         NaN
1        14.8  4  Y         7.4
2        94.0  3  Y         NaN
3        77.0  2  Y         NaN
4        12.0  1  Z         6.0

Upvotes: 1

Related Questions