geds133
geds133

Reputation: 1485

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.

Upvotes: 3

Views: 9412

Answers (2)

cvonsteg
cvonsteg

Reputation: 206

Your call of energy[:, 'Rate1E'] is doing something different to what you expect. You're looking for a .loc[] call.

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

Upvotes: 0

jpp
jpp

Reputation: 164663

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.

Upvotes: 6

Related Questions