I am trying to get the following script to work. The input file consists of 3 columns: gene association type, gene name, and disease name.
cols = ['Gene type', 'Gene name', 'Disorder name']
no_headers = pd.read_csv('orphanet_infoneeded.csv', sep=',',header=None,names=cols)
gene_type = no_headers.iloc[1:,[0]]
gene_name = no_headers.iloc[1:,[1]]
disease_name = no_headers.iloc[1:,[2]]
query = 'Disease-causing germline mutation(s) in' ###add query as required
orph_dict = {}
for x in gene_name:
if gene_name[x] in orph_dict:
if gene_type[x] == query:
orph_dict[gene_name[x]]=+ 1
else:
pass
else:
orph_dict[gene_name[x]] = 0
I keep getting an error that says:
Series objects are mutable and cannot be hashed
Any help would be dearly appreciated!
![]()
sophros
13.5k9 gold badges44 silver badges69 bronze badges
asked Apr 17, 2015 at 13:26
1
Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that’s why you get an error.
Further explanation:
Mutable objects are objects which value can be changed.
For example, list is a mutable object, since you can append to it. int is an immutable object, because you can’t change it. When you do:
a = 5;
a = 3;
You don’t change the value of a, you create a new object and make a point to its value.
Mutable objects cannot be hashed. See this answer.
To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.
answered Apr 17, 2015 at 14:42
Ella SharakanskiElla Sharakanski
2,6433 gold badges25 silver badges47 bronze badges
gene_name = no_headers.iloc[1:,[1]]
This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:
gene_name[x]
you now have a Series object with a single value. You can’t hash the Series.
The solution is to create Series from the start.
gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]
Also, where you have orph_dict[gene_name[x]] =+ 1, I’m guessing that’s a typo and you really mean orph_dict[gene_name[x]] += 1 to increment the counter.
answered Apr 17, 2015 at 14:36
jkitchenjkitchen
7959 silver badges16 bronze badges
3
Here’s everything about TypeError: Series objects are mutable and cannot be hashed in Python:
This error occurs when you use mutable objects as keys for a dictionary.
Mutable data types cannot be dictionary keys, and using them as such will raise a TypeError with the message “unhashable type”.
So if you want to learn all about what this error in Python really is about and how to solve it, then you’re in the right place.
It’s time for the first step!

What About TypeError: Series Objects Are Mutable and Cannot be Hashed in Python?
To understand the causes of the TypeError: “Series objects are mutable and cannot be hashed” error, let’s first take a look at the pandas module, as it’s easier to explain the error by using this module.
What Is the Pandas Module?

If you are getting started with data analysis, you will surely come across the pandas library.
Pandas is a convenient tool for quickly loading, processing, and saving even large amounts of tabular data.
This module is part of a group of projects sponsored by numFocus.
NumFocus supports various projects related to scientific computing, such as:
- Numpy
- Matplotlib
- Scipy
- Scikit-learn
The pandas library is well documented.
It is widely used and supported all over the world.
You can even get involved in development by fixing bugs on the project here.
You can connect the panda’s library with the following command:
import pandas
Pandas use its own specific data structures to work with data quickly and conveniently.
These structures are:
- Series
- Data frame
Series is a labeled one-dimensional data structure.
Think of it as a table with one row.
You can work with a series as a regular array (refer to the index number), and as an associated array, when you can use a key to access data items.
You can also think of a data frame as a collection of series.
Data frame is a two-dimensional labeled structure.
It is very similar to a regular table.
Thinking of a data frame as a table will help you understand how to create data frames and work with their elements, rows, and columns.
First, let’s create a series object from a list:
ser1 = pd.Series(["a", "b", "c", "d", "e"])
print(ser1)
0 a
1 b
2 c
3 d
4 e
dtype: object
This object is quite simple, but in addition to data, it contains indexes.
These indexes can be named so that it looks more like a table row. Plus, let’s put some data inside the series—data of an agent:
ser2 = pd.Series([192168, "John Smith", "agent", 120000], index=["id", "name", "job_title", "salary"])
print(ser2)
id 192168
name John Smith
job_title agent
salary 120000
dtype: object
The series object is one-dimensional—it can contain only one row.
To store multiple lines, you need a data frame.
What Are Mutable Objects and Immutable Objects in Python?
Series and data frames are both mutable data types.
All data types in Python fall into one of two categories: mutable and immutable.
Many of the predefined Python data types are immutable object types such as numeric data (int, float, complex), character strings, and tuples.
Other types are defined as mutable, such as lists, sets, and dictionaries.
Newly defined user types (classes) can be defined as immutable or mutable.
The mutability of an object of a specific type is a fundamentally important characteristic that determines whether or not an object of this type can act as a key for dictionaries.
What Are Dictionaries in Python? (3 Solutions)

Dictionaries represent one of the built-in, complexly structured types (collections) of Python (along with lists, tuples, and sets).
However, dictionaries in Python have a unique, exclusive meaning, as the Python interpreter itself is based on dictionaries, and the current namespace at the point of execution is a dictionary whose keys are object names.
The keys of the dictionary elements can be numeric values, strings, tuples, and objects of their own classes, or even functions.
What these data types have in common is that they are all immutable.
Mutable data types cannot be dictionary keys, and using them as such will raise a TypeError with the message “unhashable type”.
The exception will be thrown right at runtime because the interpreter cannot determine the hashability of the key type before actually executing it.
As it becomes clear, Python mutable data types are data types for which the value returned by the hash() function is undefined.
If you try to create a dictionary whose key is the series object from above, you get an error:
dic1 = {ser1: "Our series"}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-cc98405a72a9> in <module>()
----> 1 dic1 = {ser1: "Our series"}
/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py in __hash__(self)
1667 def __hash__(self):
1668 raise TypeError(
-> 1669 f"{repr(type(self).__name__)} objects are mutable, "
1670 f"thus they cannot be hashed"
1671 )
TypeError: 'Series' objects are mutable, thus they cannot be hashed
You can quickly check whether a particular object can be used for a key in a dictionary by trying to calculate its hash with a special hash function:
hash(ser2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-4378016f27e1> in <module>()
----> 1 hash(ser2)
/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py in __hash__(self)
1667 def __hash__(self):
1668 raise TypeError(
-> 1669 f"{repr(type(self).__name__)} objects are mutable, "
1670 f"thus they cannot be hashed"
1671 )
You can deal with this error in several ways:
#1 Option to Solve Typeerror: Series Objects Are Mutable and Cannot Be Hashed
So let’s NOT use the series object as a key.
Rather, use only one of its fields.
This method is suitable if the field value is unique—for example, some ID number.
The ser2 object has an identifier field.
It’s possible to build a dictionary with keys—the values of the id field in the series object ser2.
Let’s store the agent’s callsign in it.
But first, check whether it’s possible to calculate the hash of the id field of ser2:
hash(ser2["id"])
192168
As you can see, the hash was evaluated successfully, so it’s possible to create a dictionary with this field as a key:
dic1 = {ser2["id"]: "Tiger"}
print(dic1)
{192168: 'Tiger'}
The problem with the example above is that, according to the dictionary, it is difficult to say something about the original object.
It does not store all the data, but only the identifier, which is hard to interpret.
However, it may be even safer for the task of storing an agent’s callsign.
#2 Option to Solve Typeerror: Series Objects Are Mutable and Cannot Be Hashed
The second option is to convert the series object into some immutable type, such as a tuple.
Let’s do this and try to calculate the hash of ser2 as a tuple:
tup = tuple(ser2)
hash(tup)
-2100016149781129293
The hash computed successfully. Let’s create a new dictionary and print it:
dic2 = {tup: "Tiger"}
print(dic2)
{(192168, 'John Smith', 'agent', 120000): 'Tiger'}
Better, but index values are lost here—you can save them if you use the zip function to link the field names and their values:
tup2 = tuple(zip(ser2.index, ser2))
hash(tup2)
4742336251574250744
Okay, done. Now let’s make another dictionary:
dic3 = {tup2: "Tiger"}
print(dic3)
{(('id', 192168), ('name', 'John Smith'), ('job_title', 'agent'), ('salary', 120000)): 'Tiger'}
Looks friendly and readable, but you cannot refer to the field by its name.
To get the name of the agent, you will need to write something like this:
list(dic3.keys())[0][1][1]
John Smith
Doesn’t look very nice or convenient. It would be helpful to use another dictionary as a key.
The series object is somewhat similar to a dictionary, and you can convert it into a dictionary via the same zip:
dic4 = dict(tup2)
print(dic4)
{'id': 192168, 'name': 'John Smith', 'job_title': 'agent', 'salary': 120000}
Here, you can access values by keys, just like in the Series object:
dic4['name']
John Smith
However, the dictionary object is not hashable, like the series object:
hash(dic4)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-9b57975f1da1> in <module>()
----> 1 hash(dic4)
TypeError: unhashable type: 'dict'
So, you cannot make a dictionary with other dictionaries as the keys.
However, the collections module has a data structure that looks like a hashable, immutable dictionary called namedtuple:
from collections import namedtuple
employer = namedtuple('Employer', dic4)
em1 = employer(**dic4)
print(em1)
Employer(id=192168, name='John Smith', job_title='agent', salary=120000)
The namedtuple object is hashable, which means it can be a dictionary key:
hash(em1)
-2100016149781129293
Let’s make a dictionary based on it and display it:
dic5 = {em1: "Tiger"}
print(dic5)
{Employer(id=192168, name='John Smith', job_title='agent', salary=120000): 'Tiger'}
Now you can refer to the key fields by their names. For example, like this:
for key in dic5:
print(key.name)
print(dic5[key])
John Smith
Tiger
#3 Option to Solve Typeerror: Series Objects Are Mutable and Cannot Be Hashed
Finally, the last method.
You can create a class that will inherit from the series class, but add the hashing function to it.
You can take the hash in any way that is convenient for you.
Keep in mind that if the hash suddenly changes for some reason, this object will stop working as a key:
class MySeries(pd.Series):
def __hash__(self):
return hash(tuple(self))
myser = MySeries([192168, "John Smith", "agent", 120000], index=["id", "name", "job_title", "salary"])
hash(myser)
dic = {myser: "Tiger"}
print(dic)
{id 192168
name John Smith
job_title agent
salary 120000
dtype: object: 'Tiger'}
As you can see, the dictionary key is now an object of our new class MySeries.
You can access the values of the dictionary by key:
dic[myser]
Tiger
However, if you change the hash of your object (in the present case, you can change the id), then you will no longer be able to access the values of the dictionary:
myser['id'] = 111111
dic[myser]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-66-534b17545b32> in <module>()
1 myser['id'] = 111111
----> 2 dic[myser]
KeyError: id 111111
name John Smith
job_title agent
salary 120000
dtype: object
When you try to access a dictionary value by a modified MySeries object, you get a KeyError.
This error appears due to the storage of data in the dictionary, which is described above.
When trying to access data by key, Python calculates the hash of the given key and compares it to the hash table of the dictionary.
That is why it is forbidden to use mutable objects as keys. You’ve seen above how to get around this if you really need to, but use this method with extreme caution.
Here’s more Python support:
- 9 Examples of Unexpected Character After Line Continuation Character
- How to Solve ‘Tuple’ Object Does Not Support Item Assignment
- How to Solve SyntaxError: Invalid Character in Identifier
- ImportError: Attempted Relative Import With No Known Parent Package
- IndentationError: Unexpected Unindent in Python (and 3 More)
Ah yes, it reproduces on master
traceback:
>>> df.query("name.isnull()")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/marco/pandas-dev/pandas/core/frame.py", line 3269, in query
res = self.eval(expr, **kwargs)
File "/home/marco/pandas-dev/pandas/core/frame.py", line 3399, in eval
return _eval(expr, inplace=inplace, **kwargs)
File "/home/marco/pandas-dev/pandas/core/computation/eval.py", line 346, in eval
ret = eng_inst.evaluate()
File "/home/marco/pandas-dev/pandas/core/computation/engines.py", line 73, in evaluate
res = self._evaluate()
File "/home/marco/pandas-dev/pandas/core/computation/engines.py", line 113, in _evaluate
_check_ne_builtin_clash(self.expr)
File "/home/marco/pandas-dev/pandas/core/computation/engines.py", line 29, in _check_ne_builtin_clash
names = expr.names
File "/home/marco/pandas-dev/pandas/core/computation/expr.py", line 814, in names
return frozenset([self.terms.name])
File "/home/marco/pandas-dev/pandas/core/generic.py", line 1692, in __hash__
f"{repr(type(self).__name__)} objects are mutable, "
TypeError: 'Series' objects are mutable, thus they cannot be hashed
Python throws the error, ‘series’ objects are mutable, thus they cannot be hashed when a mutable object like array is used as dictionary key for some other object.
According to Python glossary –
Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not. Immutable objects include numbers, strings and tuples. Such an object cannot be altered.
But why hashes are so important?
Actually, Python uses hashvalues to refer a dictionary item, because hash values do not change for a given value. If the reference key is immutable object like numbers, strings, tuples etc. then we are confident that their hashes will remain the same. For example –
a = 4
a = 9
Here, the value of a is not altered, else it is recreated. That’s why it is immutable. But take this example –
myArray = []
myArray[0] = ‘Captain America’
myArray[0] = ‘Ironman’
Here, myArray remained the same for both assignments. When we change any value of list, all other values remain untouched. So, the list is not recreated else it is altered. That’s why it is mutable and can’t be used as hashes.
This code will throw error, ‘series’ objects are mutable –
superHero = [0, 1, [2]]
superHeroToColor = [
'ironman',
'hulk',
'thor'
]
for x in superHero:
print(superHeroToColor[x])
Tweet this to help others
It is because one of the element of superHero array is list.
Live Demo
This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.
Related Tags
- Error,
- python error,
- python pandas,
- python-short
The “typeerror: ‘series’ objects are mutable, thus they cannot be hashed” error is caused by hashing mutable objects where only immutable objects are supposed to be used for hashing. There are a lot more causes and their solutions described in this article.
A lot of experts’ advice with coding examples that also include in this article to provide a complete understanding.
Keep reading this article to learn about this error and how to fix it in depth.
Contents
- Why Are You Getting the “Typeerror: ‘Series’ Objects Are Mutable, Thus They Cannot Be Hashed” Error?
- – Mutable Objects Can Not Be Hashed
- – You Can Not Hash the Series
- – Pandas Dataframe
- – Use of Temp in Dataframe
- – Nan Values
- – Use of “Fillna” and “Apply”
- – Use of Reserved Methods
- – Use of PD.series Objects
- How To Fix the Error
- – Mutable Objects Can Not Be Hashed
- – By Using a Hash Protocol
- – Use the Series Objects
- – Use Tuple To Convert Mutable Objects Into Immutable Objects
- – Create a Class by Using Series
- – You Can Not Hash the Series
- – Pandas Dataframe
- – Use of Temp in Dataframe
- – Nan Values
- – Use of “Fillna” and “Apply”
- – Use of Reserved Methods
- – Use of PD.series Objects
- FAQ
- – What Is the Difference Between Mutable and Immutable Objects?
- – What Is the Hash Function?
- – Why Can’t Mutable Objects Be Hashed?
- Conclusion
Let’s understand some of the leading causes of this error.
– Mutable Objects Can Not Be Hashed
If you are working in lists in Python, you can not use any mutable objects, as mutable objects can not be hashed. If you have done that, you will face that error. In Python, the hash value is required of that object you want to use as a key in the dictionary.
– You Can Not Hash the Series
If you are working in DataFrames in Python and passing a list of columns, you would have a series of objects with a single value. Hence, you can’t hash the series.
– Pandas Dataframe
If you want to change values in DataFrame by some condition, even following the Python Pandas documentation, there could be many reasons for this typeerror. There are possibilities that your code could create a circular reference, which means changing values will affect the selection.
There could be any missing label-based or usage of some methods that don’t suit the condition and such strategies make the Pandas slow, and that error can appear. A slight mistake in brackets or missing can also lead to this error.
– Use of Temp in Dataframe
One more thing can lead you to this error if you use temp[index, ‘Any name’] in DataFrame in Pandas. As column selecting using label and boolean indexing are used here, it will not work.
– Nan Values
If you are passing the string but not the series while working in Pandas, and if you have some NaN values in your columns, you can get that error in that case too.
– Use of “Fillna” and “Apply”
If you are working in Pandas and trying to take data from a column, evaluate it with the textstat module, and then write the results in the CSV format. Here you might be writing the series before using “fillna.” And that could be the reason for the error appearing.
– Use of Reserved Methods
If you use reserved Pandas methods like .cat, you will get that error.
– Use of PD.series Objects
If your series contains other pd.objects, this could be the reason in your case, as pd.series is an unhashable type.
How To Fix the Error
Here we discovered all the possible causes of that error. Let’s find out the solutions to those errors.
– Mutable Objects Can Not Be Hashed
In your case, the simple solution to this error could be to use the immutable objects that can be hashed. As you know, mutable objects can’t be hashed, so you have to use the immutable objects as a key in the dictionary. You can use int, string, and tuple as a key.
– By Using a Hash Protocol
You can create a list that can be hashed by implementing __hash__protocol. First of all, you have to develop sub-classes of the list and then implement a hash protocol. The below coding example guides how can do this step.
Coding Example of Creating a Hashable List by Using __hash__protocol
class hashable_list(list):
def__init__(selc,*args):
if (len(args) == 1 and isinstance (args[0], iterable):
argos = argos[0].super().__init__(args)
def __hash__(self):
return hash (x for x in self)
Not you can use this list as a dictionary key as well.
– Use the Series Objects
You can also use a second method, but this is applicable if you have a unique field value like some ID number. What you need to do here is to use the series object as one of its fields, not as a key.
Here we have the ser2 object that contains the values of the ID field in the series; now, we have to make sure that we can calculate the hash of the ID field of ser2 or not.
Here we have obtained the hash value, so now we can create a dictionary with the field as a key.
dic1={ser2[“id”]: “cat”}
print(dic1)
It doesn’t store all the data in it except the identifier.
– Use Tuple To Convert Mutable Objects Into Immutable Objects
There are other methods as well where you can convert the mutable objects to an immutable type like a tuple. Let’s understand how we can use a tuple to calculate the hash of ser2 by the following coding example.
Coding Example of Using Tuple To Convert Mutable Objects Into Immutable Objects
tup=tuple(ser2)
hash(tup)
Here you can get the agent’s name by using certain codes
list(dic2.keys())
Dic2 {tup: “Cat”}
print(dic2)
Here the named tuple is immutable and can be hashed.
Employer = namedtuple(‘employer’, dic2)
Em1 = employer(**dic2)
print(em1)
Employer(id=178262, name= ‘John’, job_title = ‘writer’, salary =20000)
Here you can create another dictionary where you can refer to key fields by names.
for key in dic3:
print(key.name)
print(dic3[key])
– Create a Class by Using Series
This is another method to avoid that error if you use mutable objects. You can use series to create a class and add the hash function. The object stops working as the hash changes.
Coding Example of Creating a Class by Using Series
Class MySeries(pd.Series):
Def __hash__(self):
Return hash(tuple(self))
Myser = MySeries([768463, “John”, “writer”, “20000”), index=[“id”, “name”, “job_title”, “salary”])
hash(myser)
dic={myser: “Cat”}
print(dic)
– You Can Not Hash the Series
The solution, in this case, could be that you can create the series from the start. Even if your DataFrame is split into a training and testing dataset, you can still select individual items.
– Pandas Dataframe
If the code is creating a circular reference in your case, the first thing you should do to solve this problem is to create a mask and then apply the change. However, if you need to change the column of DataFrame, make sure that you must have DataFrame.loc.
You should also avoid loops as they make your Pandas slow. In addition, you should also replace “replace,” ‘?’ with “NaN,” and “fillna” with “means.” Furthermore, you can also use square brackets around df.loc, or if you don’t want to use the df.loc you can use a lambda expression.
df = df[lambda x: x[‘z’] == z]
– Use of Temp in Dataframe
If you are using temp[index, ‘Any name’] in DataFrame in Pandas and writing like the following:
Index = temp[‘Any name’] == ‘?’
Temp[index, ‘Any name’] = mean
You should change the above code with the below code:
S = temp[‘Any name’]
temp[‘Any name’]=s.where(s!=’?’,mean)
Here were (s!=’?’,mean) means if the condition s!=’?’ meet, the element’s value will be changed to mean.
– Nan Values
The simple solution could be not to add the NaN values to the column.
– Use of “Fillna” and “Apply”
If you are making a mistake of writing the series first and then using “fillna” and “apply,” then you must make a few changes in your code, and use “fillna” and “apply” first and then write the series to the CSV.
Here you should use the “fillna” and “apply” and then write that series to the CSV. This is how your column will be taken, evaluated with the textstat module, and reported correctly to the CSV format.
Apart from that, in that condition, if you don’t want to append the column to the end, you can just add a column to the existing DataFrame/CSV. And in the future, you can fix the implementation; you can use “fillna” and write the header only on the first iteration.
– Use of Reserved Methods
You can not use the reserved methods for Pandas in your code. If you are using .cat method, you can use [‘cat’] to access the column.
– Use of PD.series Objects
Your series should be of a fixed type to allow you to perform manipulations without checking the type. An excellent solution to this could be using the function to convert pd.series in such kinds that can be hashed.
FAQ
– What Is the Difference Between Mutable and Immutable Objects?
Mutable objects can change their values, while immutable objects are objects that can not change their values over time. The list is an example of mutable objects, as we can append it, while the int is an example of immutable objects as we can’t change it.
– What Is the Hash Function?
The hash function is a built-in function in Python that returns the hash value of an object, but this happens only if the object has a value.
– Why Can’t Mutable Objects Be Hashed?
The value of its object calculates the hash. The mutable objects don’t have a fixed value, and the value keeps changing, so to calculate the hash, one needs to calculate its hash again after each change. If an object is compared equal with another one, after a change, it becomes unequal; that’s why mutable objects are not hashable and compared by value, not by hash.
Conclusion
Let’s conclude what we learned today.
- The leading cause of this error is using the mutable objects, as they are not hashable.
- You can create a python hashable list by implementing hash protocols.
- You can use a tuple to convert mutable objects into immutable.
We discovered all the causes and solutions of the “typeerror: ‘series’ objects are mutable, thus, they cannot be hashed” error. Now you have understood every solution if that error appears.
- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
![]()
The error “Series Objects Are Mutable and Cannot be Hashed” can be hard to understand if you aren’t aware of advanced data structures like hash tables. In this article, we will do our best to help you get the hang of them and how it is related to our issue.
Reproduce The Error
For instance, we have this DataFrame:
import pandas as pd
df = pd.DataFrame(
[
['LearnShareIT', 'Quora', 'Reddit', 'Stack Overflow'],
['tutorials', 'Q&A', 'Forum', 'Q&A']
]
)
print(df)
Output:
0 1 2 3
0 LearnShareIT Quora Reddit Stack Overflow
1 tutorials Q&A Forum Q&A
And we write this code to get the ranking of each site using values stored in another dict:
myDict = {
'LearnShareIT': 1,
'Quora': 2,
'Reddit': 3,
'Stack Overflow': 4
}
for x in df[:1]:
key = df[:1][x]
print(myDict.get(key))
However, we run into this error instead:
Series objects are mutable and cannot be hashed
To know why it happens, you must get an understanding of hashable objects in Python.
Hash Functions And Hash Tables
Hashing is a popular technique in computing used to identify an object from a larger group of similar objects. It makes use of hash functions and hash functions.
A hash table contains key-value pairs. In many cases, we can use the key to directly retrieve the corresponding value. However, this isn’t always feasible. A hash function is called on this key, producing a unique value for the key.
We can store this hash value alongside its value in the hash table, allowing us to access data more efficiently. With hash tables, we can reduce complex objects to simpler associative arrays.
Hashable Objects In Python
An object in Python is called hashable if it is associated with a constant hash value throughout its lifetime. These objects have a __hash__() method, which returns this hash value.
We can use hashable objects as keys in dictionaries and members in sets. Those data structures need to use hash values under the hood to access and modify internal data.
The most important thing you need to remember is that not every Python object is hashable. Most immutable objects are and have a __hash__() method:
As you can see, the hash function reduces Python strings to numbers.
Mutable containers (dictionaries and lists) are not hashable. You will run into when calling the __hash__() method:
lists
>>> c = [1, 2, 3]
>>> c.__hash__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
dicts
>>> d = {'name': 'LearnShareIT', 'type': 'tutorials'}
>>> d.__hash__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
Immutable containers like frozensets and tuples can be hashable or not, It depends on whether their elements are hashable.
Tuples with hashable elements
>>> e = (1, 2, 'LearnShareIT')
>>> e.__hash__()
-2023910400398544926
Tuples with unhashable elements
>>> f = (1, [2, 3])
>>> f.__hash__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Solution
Python requires you to use hashable objects as keys in a dictionary. This way, it can quickly loop up the values of those keys by using their hash values. Since we use Series (which are unhashable), Python returns the error instead.
We must convert it to hashable objects (like strings) first:
for x in df[:1]:
key = df[:1][x][0]
print(myDict.get(key))
Output:
1
2
3
4
Summary
The error “Series Objects Are Mutable and Cannot be Hashed” occurs when you use Series as keys to obtain values from a dictionary. Pandas Series aren’t hashable and can’t be used for such purposes.
Maybe you are interested in similar errors:
- SyntaxError: Missing parentheses in call to ‘print’ in Python
- Reindexing only valid with uniquely valued Index objects

My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: Java, C#, C, Javascript, R, Typescript, ReactJs, Laravel, SQL, Python
In Python, there is an error as TypeError: Series Objects Are Mutable that arises when you use mutable objects as a key for the dictionary. Mutable objects are those whose values can change and you do not have to reassign them to the same variable. let’s go and fix TypeError: Series Objects Are Mutable by using four easy method.
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 changes its value at some point in the code.
Contents
- 1 How to Fix “TypeError: Series Objects Are Mutable” In Python?
- 1.1 Method 1
- 1.2 Method 2
- 1.3 Method 3:
- 1.4 Method 4
- 1.5 How to solve Series’ objects are mutable and cannot be hashed
- 1.6 Typeerror: series name must be a hashable type
Series objects in Python are mutable. This means that you can change the value of any element at any time, even while it’s being returned by calling next() on your Series object!
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)
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 the 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())
dic2 {tup: "Lion"}
print(dic2)
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.
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
How to solve Series’ objects are mutable and cannot be hashed
Series objects are mutable and cannot be hashed because they are not stored in the database as hash values. Instead, they are stored as object references so that you can access them by name.
objects are mutable and cannot be hashed because they are not stored in the database as hash values. Instead, they are stored as object references so that you can access them by name.
When you create a series, Django creates a new Python list and inserts your object reference into the list. The list is then returned to you, and you can use it to access your object by name.
Since lists are mutable, you can change the contents of the list without affecting the underlying object reference.
Typeerror: series name must be a hashable type
When you get a TypeError that says “series name must be a hashable type”, it means that pandas can’t find an appropriate way to store your data in memory. This might happen if, for example, you try to use a Series or DataFrame as a key in a dictionary.
To fix this, you need to make sure that your series or data frame has a hashable type. A hashable type is something that can be turned into a number (usually by using the hash function). The most common hashable types are numbers, strings, and tuples. But there are also some more obscure ones like sets and frozen sets.