Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: unhashable type: 'slice' pandas DataFrame column

This is probably simple but I cant find the explanation and it happens to me all the time.

I am trying to selected values from column Rate1E that are over 3.5 and view the rest of the rows in pandas DataFrame energy for selected rows meeting criteria as stated above. I had someone give me an answer before and have simply changed to text as follows:

energy = energy.loc[energy[:, 'Rate1E'] >= 3.5]
print(energy.loc[:, 'Rate1E'])

However once again I have found myself with the error:

TypeError: unhashable type: 'slice'

Online solutions suggest .loc is the answer. Would someone know how to fix the code or better yet explain to me why I always seem to get that error.

Thanks.

like image 359
geds133 Avatar asked Jul 17 '26 20:07

geds133


1 Answers

Your syntax is incorrect. You need:

energy = energy.loc[energy['Rate1E'] >= 3.5]

Alternatively:

energy = energy.loc[energy.loc[:, 'Rate1E'] >= 3.5]

The crucial point is energy.loc[:, 'Rate1E'] and energy['Rate1E'] are series, the latter being a convenient way to access the former.

It is unfortunate, but the Pandas documentation doesn't specify precisely permitted arguments for pd.DataFrame.__getitem__, for which df[] is syntactic sugar. The most popular uses are:

  • Provide a string to give a series.
  • Provide a list to give a dataframe.
  • Provide a Boolean series to filter your dataframe.
like image 106
jpp Avatar answered Jul 20 '26 10:07

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!