Are you dealing with “typeerror: unhashable type: ‘dataframe'” error message and don’t know how to fix?
In this article, we will delve into the solutions of “unhashable type: ‘dataframe'” error message.
Just keep on reading if you wanted to get rid of this error.
What is DataFrame?
A “DataFrame” is a two-dimensional labeled data structure with columns of potentially different types.
Some of the key features of DataFrames are the following:
✔Columns
Each column has a name and data type, such as integer, float, or string.
✔Rows
Each row is labeled with a unique index and contains data for each column.
✔Index
The index is used to label the rows of the DataFrame and can be either integers or labels.
✔ Missing Values
DataFrames can handle missing values, which are typically represented as NaN (not a number).
✔ Filtering and Sorting
DataFrames can be filtered and sorted by various criteria.
What is “typeerror: unhashable type: ‘dataframe'”?
The “typeerror: unhashable type: ‘dataframe'” is an error message that occurs in Python when you are trying to use a DataFrame object as a key in a dictionary or as an element in a set.
For example:
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({'A': [10, 20, 30], 'B': [40, 50, 60]})
# use the DataFrame as a key in a dictionary
x = {df: 'value'}
# print the dictionary
print(x)
If we run this example code, it throw an error message:
TypeError: unhashable type: 'DataFrame'
This is because DataFrames are mutable objects and cannot be hashed.
Hashing is the process of converting an object into a fixed-size integer that can be used as an index in a hash table.
As a result, they cannot be hashed, which is a requirement for objects to be used as keys in a dictionary or elements in a set.
The “hashable” objects are:
✅ bytes
✅ bool
✅ complex
✅ decimal
✅float
✅ frozenset
✅ int
✅ range
✅ string
✅ tuple
The “unhashable” objects are:
✔ bytearray
✔ customclasses
✔ dict
✔ list
✔ set
Why does this error occur?
Here are the several common causes of the error:
- Attempting to hash a dataframe
- Assigning a dataframe as a key in a dictionary
- Passing a dataframe as an argument to a function that doesn’t support it.
How to fix “typeerror: unhashable type: ‘dataframe'”?
To fix this error, you have to convert the DataFrame to a hashable object, such as a tuple, using the tuple() function.
This will create a new, immutable object that can be used as a key in a dictionary or as an element in a set.
Here are the following solutions that you can use to fix the error:
1. Convert the DataFrame to a tuple
You can easily convert the DataFrame to a tuple, which is an immutable object and can be used as a key in a dictionary or as an element in a set.
For example:
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30], 'B': [40, 50, 60]})
t = tuple(map(tuple, df.values))
x = {t: 'value'}
print(x)
Output:
{((10, 40), (20, 50), (30, 60)): 'value'}
2. Convert the DataFrame to a string
Another way to make the DataFrame hashable is to convert it to a string using the to_string() method.
For example:
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({'A': [10, 20, 30], 'B': [40, 50, 60]})
# convert the DataFrame to a string
df_str = df.to_string(index=False)
# use the string as a key in a dictionary
x = {df_str: 'value'}
# print the dictionary
print(x)
Output:
{' A B\n10 40\n20 50\n30 60': 'value'}
3. Use the DataFrame’s columns as keys
Instead of using the entire DataFrame as a key, you can also use its columns as keys in the dictionary.
For example:
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30], 'B': [40, 50, 60]})
d = {col: df[col].tolist() for col in df.columns}
print(d)
Output:
{'A': [10, 20, 30], 'B': [40, 50, 60]}
4. Flatten the DataFrame
You can also flatten the DataFrame into a one-dimensional array and use that as a key in the dictionary or as an element in the set.
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30], 'B': [40, 50, 60]})
flat = df.values.flatten()
x = {tuple(flat): 'value'}
print(x)
Output:
{(10, 40, 20, 50, 30, 60): 'value'}
5. Use a different data structure
Alternatively, instead of using a dictionary or set, you can also use a different data structure that allows mutable objects like DataFrames.
For instance, you can use a list of tuples where the first element of each tuple is the DataFrame and the second element is the value associated with it.
For example:
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30], 'B': [40, 50, 60]})
x = [(df, 'value')]
print(x)
Output:
[( A B
0 10 40
1 20 50
2 30 60, 'value')]
Conclusion
The “typeerror: unhashable type: dataframe” is an error message that occurs in Python when you are trying to use a DataFrame object as a key in a dictionary or as an element in a set.
This article already provides several solutions above so that you can fix the error message immediately.
We are hoping that this article provided you with sufficient solutions to get rid of the error.
You could also check out other “typeerror” articles that may help you in the future if you encounter them.