In this article, we will discuss the “Typeerror: unhashable type: ‘series'”, provide the possible causes of this error, and give solutions to resolve this error.
So first, let us know what this error means.
What does typeerror: unhashable type: ‘series’ means?
This “typeerror: unhashable type: ‘series'” is an error message indicating that you are trying to use a pandas Series as a key in a dictionary or as an element in a set.
Hashable Types
In Python, hashable types are those that can be converted to a unique integer value, such as strings, integers, and tuples.
The built-in hash() function is used to convert an object into a hash value.
Here is an example of hashable types of integer in Python:
hash(5) # returns 5
Immutable Objects
In Python, an immutable object is an object whose state cannot be modified after it is created.
Immutable objects are useful because they are safer to use in multi-threaded code.
This can be used as keys in dictionaries and can be used in other contexts where mutability is not desirable.
Here is an example of immutable objects of numbers in Python:
x = 5
y = 10.0
z = 2 + 3j
x += 1 # This creates a new object with the value of 6
y *= 2 # This creates a new object with the value of 20.0
z = 4 + 5j # This creates a new object with the value of 4 + 5j
Note: Mutable objects such as lists and dictionaries are not hashable because their contents can change, which would affect their hash value.
Why does this typeerror: unhashable type: ‘series’ happen?
This “typeerror: unhashable type: ‘series'” error occurs in Python when you try to use a Pandas Series object in a context where a hashable object is expected.
Hashable objects are those that have a fixed hash value that does not change during their lifetime.
They can be used as keys in dictionaries or as elements in sets.
Here are the causes of why this error occurs:
Cause 1: Assigning Series Objects to Dictionary Keys, Set Elements, or Pandas Index Values.
In Python, dictionary keys, set elements, and Pandas Index values must be hashable.
It means that they need to have a fixed hash value that remains constant throughout their lifetime.
Pandas Series objects are mutable, which means that their values can change over time.
Therefore, attempting to use a Series object in these contexts will result in the “TypeError: unhashable type: ‘Series'” message.
Here is an example code:
import pandas as pd
# create a Pandas Series object
s = pd.Series([1, 2, 3])
# try to use the Series object as a key in a dictionary
d = {s: ["one", "two", "three"]}
# try to use the Series object as an element in a set
s1 = set([s])
Output
TypeError: unhashable type: 'Series'
Cause 2: Slice DataFrame incorrectly
Another cause of the “Type Error: unhashable type: ‘Series'” is when you slice a DataFrame incorrectly.
A DataFrame is a two-dimensional data structure in Pandas, consisting of rows and columns.
When you slice a DataFrame, you can select rows or columns using the iloc or loc accessor.
However, if you slice a DataFrame in a way that results in a Series object, and then try to use that Series object as a hashable object, you an error message.
Here is an example
import pandas as pd
from collections import defaultdict
subjects = pd.DataFrame(
data=[
["Mathematics", "Juan Dela Cruz"],
["Science", "Justin Vasquez"],
["English", "Justin Vasquez"],
["Networking", "Joana Mabayan"],
["General Mathematics", "Juan Dela Cruz"],
],
columns=["Subject", "Profesor"],
)
# Use defaultdict to initialize every value with a 0
mentions = defaultdict(int)
for i in range(len(subjects)):
Profesor_name = subjects.loc[i, ["Profesor"]] # attempts to get the Profesor's name for every row i
mentions[Profesor_name] += 1 # for every mention of a Profesor, add 1 to its count
print(mentions)
Output
TypeError: unhashable type: 'Series'
Cause 3: Not Unpacking Iterrows
When iterating through a Pandas DataFrame using the iterrows() method, each row is returned as a tuple containing the row index and a Series object representing the row data.
If we forget to unpack this tuple and try to use the Series object directly, we can get the “Typeerror: unhashable type: ‘series’ “.
Here is an example code snippet:
Let’s use this scenario using the subjects DataFrame again:
subjects = pd.DataFrame(
data=[
["Mathematics", "Juan Dela Cruz"],
["Science", "Justin Vasquez"],
["English", "Justin Vasquez"],
["Networking", "Joana Mabayan"],
["General Mathematics", "Juan Dela Cruz"],
],
This time, we’ll use iterrows() to iterate through the DataFrame.
mentions = defaultdict(int)
# Using iterrows now
for row in subjects.iterrows():
Profesorr_name = subjects.loc[row, "Profesor"]
another_dict[key] += 1
print(mentions)
Output
TypeError: unhashable type: 'Series'
Now let’s fix this Error.
Typeerror: unhashable type: ‘series’ – Solutions
Here are the alternative solutions that you can use to fix “Typeerror: unhashable type: ‘series'”:
Solution 1: Used namedtuple
We need to replace the Series object with a hashable data type.
One suitable alternative to the Series object is a namedtuple, which also uses key-value pairing and is hashable.
A named tuple is a subclass of a tuple that allows the elements to be accessed by name as well as by index.
It is defined using the namedtuple function from the collections module.
Here is the example code and solution to the first cause of “unhashable type: ‘series'” error that used namedtuple:
import pandas as pd
from collections import namedtuple
s = pd.Series(data=[1, 2, 3], index=["one", "two", "three"])
# names the tuple 'series1' and matches s1's indices with its values.
nt = namedtuple("series", s.index)(*s)
print(nt)
Output
series(one=1, two=2, three=3)
Solution 2: Convert the row Series object to a hashable data type
To fix “Typeerror: unhashable type: ‘series'”, we can convert the row Series object to a hashable data type, such as a tuple, before using it as a key in a dictionary.
Here is an updated code:
import pandas as pd
from collections import defaultdict
subjects = pd.DataFrame(
data=[
["Mathematics", "Juan Dela Cruz"],
["Science", "Justin Vasquez"],
["English", "Justin Vasquez"],
["Networking", "Joana Mabayan"],
["General Mathematics", "Juan Dela Cruz"],
],
columns=["Subject", "Profesor"],
)
# Use defaultdict to initialize every value with a 0
mentions = defaultdict(int)
for i in range(len(subjects)):
Profesor_name = subjects.loc[i, "Profesor"] # stripped the ['Profesor'] from the brackets
mentions[Profesor_name] += 1
print(mentions)
Output
defaultdict(<class 'int'>, {'Juan Dela Cruz': 2, 'Justin Vasquez': 2, 'Joana Mabayan': 1})
Solution 3: Unpack Iterrows
We need to unpack the tuple returned by iterrows() and use the Series object’s values instead of the object itself.
Here is an example:
import pandas as pd
from collections import defaultdict
subjects = pd.DataFrame(
data=[
["Mathematics", "Juan Dela Cruz"],
["Science", "Justin Vasquez"],
["English", "Justin Vasquez"],
["Networking", "Joana Mabayan"],
["General Mathematics", "Juan Dela Cruz"],
],
columns=["Subject", "Profesor"],
)
# Use defaultdict to initialize every value with a 0
mentions = defaultdict(int)
# Using iterrows now
for index, row in subjects.iterrows():
Profesor_name = subjects.loc[index, "Profesor"]
mentions[Profesor_name] += 1
print(mentions)
Output
defaultdict(<class 'int'>, {'Juan Dela Cruz': 2, 'Justin Vasquez': 2, 'Joana Mabayan': 1})
Here are the other fixed python errors that you can visit, you might encounter them in the future.
- Attributeerror module tensorflow compat v1 has no attribute contrib
- Attributeerror: module ‘collections’ has no attribute ‘iterable’
- Attributeerror module has no attribute
Conclusion
In conclusion, in this article, we discuss “Typeerror: unhashable type: ‘series’”, state the causes of this error, and provide solutions that resolve the error.
By following the given solution, surely you can fix the error quickly and proceed to your coding project again.
I hope this article helps you to solve your problem regarding a TypeError stating “unhashable type series”
We’re happy to help you.
Happy coding! Have a Good day and God bless.