How to Fix “TypeError: Series Objects Are Mutable” In Python?

In Python, there is an error as Type Error that arises when you use mutable objects as a key for the dictionary. Mutable objects are those whose value can change and you do not have to reassign it to the same variable.

The hash value is a number that we get by using some operation on an object. As hashing,, an object means the object must have a constant and fixed particular value throughout the whole session. As the mutable object
change its value at some point in the code.

How to Fix “TypeError: Series Objects Are Mutable” In Python?

It causes a change in the hash value as well. It tells us that we cannot hash a list because the values in a loss can be changed while we can hash strings and integers as their value is fixed and does not change without reassigning it to a variable.

Here are some methods that can be used to fix this error in Python,

Method 1

We just have to implement __hash__protocol to create a list that can be hashed. This can be done by sub-classing the list and then implementing a hash protocol in it.

Here are some steps that you have to follow from collections import Iterable


class hashable_list(list):  
def __init__(self, *args):  
if len(args) == 1 and isinstance(args[0], Iterable):  
args = args[0] 
super().__init__(args)  
def __hash__(self):  
return hash(x for x in self)

This list can be used as a dictionary key.

Method 2

This method is used when the field value is unique like some ID number. In this method, we have to use the series object as one of its fields not as a key.

We have a ser2 object having values of id field in the series, and now, we will check if it is possible to calculate the hash of the id field of ser2 or not. We will try to store the call sign of the agent in it.


hash(ser2[‘id”])
176450

Here we have obtained a hash value so it shows that we can create a dictionary with the field as a key.


dic1 = {ser2[“id”] : “Lion”}
print(dic1)
{176450 : ‘Lion’}

This method is the best way to keep the data of an agent’s call sign.

On the other hand, it is not easy to tell about the original object in a dictionary, and it does not store all data in it except identifier.

Method 3:

You can convert the series of a mutable object into an immutable type such that in the form of a tuple. We will use a tuple to calculate the hash of ser2 by following these functions.

tup = tuple(ser2)
hash(tup)

We can get the name of the agent also by using certain codes.

List(dic2.keys())
William
dic2 {tup: “Lion”}
print(dic2)

{(176450, ‘William’ , ‘agent’ , 12000) : ‘Lion’}

namedtuple is a hashable and immutable dictionary and we will use it now. from collections import namedtuple


employer = namedtuple('Employer', dic2)
em1 = employer(**dic2)
print(em1)
Employer(id=176450, name='William', job_title='agent',
salary=12000)

  • Now, we will make another dictionary as dic3 in which you can refer to key fields by names.

dic3 = {em1: “Lion”}
print(dic3)
{Emplyer(id=176450, name=’William’, job_title=‘agent’,
salary=12000): ‘Lion’}
for key in dic3:
print(key.name)
print(dic3[key])

OUTPUT

William
Lion

Method 4

In this method, series will be used to create a class and then add hashing function to it. And if the hash changes, the object will stop working as a key.


class MySeries(pd.Series):
def __hash__(self):
return hash(tuple(self))
myser = MySeries([176450, "William", "agent", 12000],
index=["id", "name", "job_title", "salary"])
hash(myser)
dic = {myser: "Lion"}
print(dic)
{id 176450

name William
job_title agent
salary 12000
dtype: object: 'Lion'}

Here, the dictionary key is an object of the new class MySeries but if you change the hash it will show no results and give Key Error.

Read more: How to Read Text File Line By Line Using Python

Leave a Comment