Python series objects are mutable thus they cannot be hashed

‘series’ objects are mutable, thus they cannot be hashed – Python Error

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.

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 –

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])

It is because one of the element of superHero array is list.

Live Demo

  • syntaxerror: unexpected eof while parsing Python – Code…
  • python run bash script in background
  • Python string substring, contains, find and index comparison
  • ‘int’ object is not iterable – Python Error
  • ‘float’ object cannot be interpreted as an integer – Python…
  • Sorting a dictionary by value in Python
  • ‘python’ is not recognized as an internal or external…
  • ‘str’ object does not support item assignment – Python Error
  • Pandas iterate over rows – Python
  • ‘str’ object is not callable – Python Error
  • Convert list to string in Python
  • ‘float’ object is not callable – Python TypeError
  • ‘dict’ object has no attribute ‘iteritems’, ‘iterkeys’ or…
  • TypeError: a bytes-like object is required, not ‘str’ Python…
  • Only length-1 arrays can be converted to python scalars

Источник

Python groupby error, ‘unhashable’ Series object

I have a Pandas DataFrame of values (floats) and country name strings («UNITED STATES», «UNITED KINGDOM», etc). I want to sum the values based on the countries:

Data['Values'].groupby(Data['Country']).sum() 
TypeError: 'Series' objects are mutable, thus they cannot be hashed 
TypeError: 'Series' objects are mutable, thus they cannot be hashed 

Why is this error occurring? Is it something about the country names? Any help would be greatly appreciated. I am using Python 3.4 and Pandas 0.15.2.

I think your approach is a little different than most, but this should still work. if you do a Data[‘Country’].dtype what do you get?

@crow_t_robot, true, I haven’t paid enough attention to see your error, although not correct to groupby using Data[‘Values’] , you should get KeyError instead. Can you show what type(Data) is?

type(Data) gives me «pandas.core.frame.DataFrame». Even using Data instead of Data[‘Values’] produces the same TypeError, however.

1 Answer 1

Sometimes mutable types like lists (or Series in this case) can sneak into your collection of immutable objects.

You can use apply to force all your objects to be immutable. Try

Data.Country = Data.Country.apply(str) Data.groupby('Country').Values.sum() 

Note that this can result in strings not being what you expected them to be; e.g. str([‘Canada’]) -> «[‘Canada’]» so str([‘Canada’]) == ‘Canada’ will yield False . I recommend doing Data.Country.unique() and at least visually inspecting to make sure that everything looks as it should.

Источник

when I set value in dataframe(pandas) there is error: ‘Series’ objects are mutable, thus they cannot be hashed

enter image description here

this is jupyter notebook give me error: I want to know how to change value in dataframe and why my way is wrong? Could you help me, I look forward your help!!

2 Answers 2

For last line add DataFrame.loc , because need change column of DataFrame :

temp.loc[index,'Bare Nuclei'] = mean 

But in pandas is the best avoid loops, because slow. So better solution is replace ? to NaN s and then fillna by mean s:

data['Bare Nuclei'] = data['Bare Nuclei'].replace('?', np.nan).astype(float) #more general #data['Bare Nuclei'] = pd.to_numeric(data['Bare Nuclei'], errors='coerce') data['Bare Nuclei'] = data['Bare Nuclei'].fillna(data['Bare Nuclei'].mean()) 
mask = data['Bare Nuclei'] == '?' data['Bare Nuclei'] = data['Bare Nuclei'].mask(mask).astype(float) data['Bare Nuclei'] = data['Bare Nuclei'].fillna(data['Bare Nuclei'].mean()) 
column_names = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape', 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli', 'Mitoses', 'Class'] data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data', names = column_names ) #print (data.head()) 
#get index values by condition L = data.index[data['Bare Nuclei'] == '?'].tolist() print (L) [23, 40, 139, 145, 158, 164, 235, 249, 275, 292, 294, 297, 315, 321, 411, 617] #get mean of values converted to numeric print (data['Bare Nuclei'].replace('?', np.nan).astype(float).mean()) 3.5446559297218156 print (data.loc[L, 'Bare Nuclei']) 23 ? 40 ? 139 ? 145 ? 158 ? 164 ? 235 ? 249 ? 275 ? 292 ? 294 ? 297 ? 315 ? 321 ? 411 ? 617 ? Name: Bare Nuclei, dtype: object #convert to numeric - replace `?` to NaN and cast to float data['Bare Nuclei'] = data['Bare Nuclei'].replace('?', np.nan).astype(float) #more general #data['Bare Nuclei'] = pd.to_numeric(data['Bare Nuclei'], errors='coerce') #replace NaNs by means data['Bare Nuclei'] = data['Bare Nuclei'].fillna(data['Bare Nuclei'].mean()) 
#verify replacing print (data.loc[L, 'Bare Nuclei']) 23 3.544656 40 3.544656 139 3.544656 145 3.544656 158 3.544656 164 3.544656 235 3.544656 249 3.544656 275 3.544656 292 3.544656 294 3.544656 297 3.544656 315 3.544656 321 3.544656 411 3.544656 617 3.544656 Name: Bare Nuclei, dtype: float64 

Источник

Читайте также:  Php имя выполняемой функции
Оцените статью