Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 4 TypeError:unhashable type:'slice' #76

Open
chenlee1990 opened this issue Jun 29, 2021 · 1 comment
Open

Chapter 4 TypeError:unhashable type:'slice' #76

chenlee1990 opened this issue Jun 29, 2021 · 1 comment

Comments

@chenlee1990
Copy link

when I write this line
berri_bikes.loc[:, 'weekday'] = berri_bikes.index.weekday

If we run then we will see the bug: TypeError:unhashable type:'slice'

Anyone can tell me what happen and how to fix the bug?

@aishwaryanevrekar
Copy link

The bug in the code berri_bikes.loc[:, 'weekday'] = berri_bikes.index.weekday is that the slice [:, 'weekday'] is unhashable.

A hashable type is a type that can be used as a key in a dictionary or a set. Slices are not hashable because they are not immutable. This means that they can be changed after they are created.

To fix the bug, you need to use a different way to slice the berri_bikes DataFrame. One way to do this is to use the iloc attribute. The iloc attribute allows you to slice a DataFrame by integer location.

The following code will fix the bug:

Python
berri_bikes.loc[:, 'weekday'] = berri_bikes.index.iloc[:, -1]
Use code with caution. Learn more
The -1 in the iloc slice tells Python to select the last column of the berri_bikes DataFrame.

Another way to fix the bug is to convert the berri_bikes.index.weekday series to a list before slicing it. The following code will also fix the bug:

Python
berri_bikes.loc[:, 'weekday'] = list(berri_bikes.index.weekday)
Use code with caution. Learn more
Which method you choose to use is a matter of personal preference. However, the iloc method is generally more efficient and easier to read.

Used bard btw for this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants