Solve type error method not subscriptable in DataFrames
This exception occurs when using the bracket notation to call a Python (or one of its libraries – such as pandas for example) method. A subscriptable object is one that encapsulates other objects, such as a list, tuple or dictionary. Pandas DataFrame methods are not – hence the error.
Reproducing the problem
Assume you have the following DataFrame:
import pandas as pd
language = ['Java', 'Javascript', 'Java']
office = ['Los Angeles', 'New York', 'Paris']
salary = [116.0, 170.0, 82.0]
salaries = dict(office = office, language = language, salary = salary)
salaries_df = pd.DataFrame(data=salaries)
print (salaries_df)
This will return the following DataFrame rows:
office | language | salary | |
---|---|---|---|
0 | Los Angeles | Java | 116.0 |
1 | New York | Javascript | 170.0 |
2 | Paris | Java | 82.0 |
Let’s assume that we would like to drop one or more DataFrame columns – in this case the language column.
salaries_df.drop['language']
This will return the following exception
TypeError: 'method' object is not subscriptable
Here’s a screenshot from Jupyter – you will receive similar messages in VSCode, PyCharm, Spyder or other Python development environments.
Solving the problem
Luckily fixing this issue is simple. Just use parentheses instead of brackets:
salaries_df.drop('language')
Type not subscriptable in pandas Groupby
In a similar fashion you can encounter the same error on pandas Groupby objects. Let’s assume that we would like to obtain the average salary for each of the programming languages in our data set.
salaries_df.groupby['language'].mean()
This will throw a typeerror exception.
Solution, as we have seen before, is to use parentheses instead of brackets:
salaries_df.groupby('language').mean()
This will return the following DataFrame:
salary | |
---|---|
language | |
Java | 99.0 |
Javascript | 170.0 |