pandas-cookbook
pandas-cookbook copied to clipboard
Chapter 4 TypeError:unhashable type:'slice'
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?
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