Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Series objects are mutable and cannot be hashed" error

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!

like image 731
Sal Avatar asked Apr 17 '15 13:04

Sal


People also ask

Can mutable objects be hashed?

They all compare unequal (except with themselves), and their hash value is derived from their id(). This feels somewhat weird... so user-defined mutable objects are hashable (via this default hashing mechanism) but built-in mutable objects are not hashable.

Are series mutable?

All Pandas data structures are value mutable (can be changed) and except Series all are size mutable. Series is size immutable.

Can you hash mutable types?

The only exception when you can have a mutable, hashable class is when the hash is based on the identity and not the value, which severely restricts its usefulness as a dictionary key.

Are pandas series hashable?

Pandas Series is nothing but a column in an excel sheet. Labels need not be unique but must be a hashable type.


1 Answers

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.

like image 83
Ella Sharakanski Avatar answered Sep 21 '22 23:09

Ella Sharakanski