Python Forum
TypeError: unhashable type: 'Series' - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: TypeError: unhashable type: 'Series' (/thread-41755.html)



TypeError: unhashable type: 'Series' - bongielondympofu - Mar-14-2024

I get the TypeError: unhashable type: 'Series' when running the code. The dataset does have a column called 'Date' The code is below
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data.csv")
date = input("What date would you like to view? (dd/mm/yyyy)\nEnter:  ")
df1 = df.loc(df["Date"] == date)
print(df1)
However the line below works;
[df1 = (df.loc[df.Date == date])



RE: TypeError: unhashable type: 'Series' - Pedroski55 - Mar-14-2024

Try like this:

df = pd.read_csv("/home/pedro/myPython/pandas/csv_files/get_data_by_date.csv")
date = input("What date would you like to view? (dd/mm/yyyy)\nEnter:  ")
date # returns '03/09/23'
df['Date'][2] # returns '03/09/23'
df.loc[df['Date'] == date] # returns the row where Date = '03/09/23'



RE: TypeError: unhashable type: 'Series' - deanhystad - Mar-14-2024

The reason "df.loc(df["Date"] == date)" doesn't work is because that is not how you use loc. If you read the documentation you'll see that your second example is the correct syntax for using loc, other than the surrounding parenthesis that do nothing.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html

Are you looking for more explanation than "You are using it wrong"? I can take a shot.

DataFrame.loc is not a function, it is an object. In particular it is a _LocIndexer object. You can see that if you write something like this
import pandas as pd
df = pd.DataFrame()
print(df.loc)
Output:
<pandas.core.indexing._LocIndexer object at 0x0000017ACE809030>
This class has a special method named __getitem__() that gets called when you use square brackets like this: df.loc[df.Date == date]. __getitem__() is one of many Python dunder methods (or magic methods) that are used to associate operators like [], >, + with methods __getitem__, __gt__, __add__.

There is another dunder method __call__ that gets called when you follow an instance by (). This is what happened in your first example. When you did this: df.loc(df["Date"] == date) you were actually doing this: df.loc.__call__(df["Date"] == date).

Your program crashed because you accidentally called loc.__call__() when you meant to call loc.__getitem__().