17 авг. 2022 г.
читать 1 мин
Одна распространенная ошибка, с которой вы можете столкнуться при использовании pandas:
TypeError : 'DataFrame' object is not callable
Эта ошибка обычно возникает, когда вы пытаетесь выполнить какое-либо вычисление переменной в кадре данных pandas, используя круглые () скобки вместо квадратных скобок [ ] .
В следующем примере показано, как использовать этот синтаксис на практике.
Как воспроизвести ошибку
Предположим, у нас есть следующие Pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
'points': [18, 22, 19, 14, 14, 11, 20, 28],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
#view DataFrame
print(df)
team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 D 14 9 6
4 E 14 12 6
5 F 11 9 5
6 G 20 9 9
7 H 28 4 12
Теперь предположим, что мы пытаемся вычислить среднее значение в столбце «баллы»:
#attempt to calculate mean value in points column
df('points').mean()
TypeError : 'DataFrame' object is not callable
Поскольку мы использовали круглые () скобки, pandas считает, что мы пытаемся вызвать DataFrame как функцию.
Поскольку DataFrame не является функцией, мы получаем ошибку.
Как исправить ошибку
Чтобы устранить эту ошибку, просто используйте квадратные [] скобки при доступе к столбцу точек вместо круглых () скобок:
#calculate mean value in points column
df['points'].mean()
18.25
Мы можем вычислить среднее значение столбца точек (18,25) без каких-либо ошибок, поскольку мы использовали квадратные скобки.
Также обратите внимание, что мы могли бы использовать следующую точечную нотацию для вычисления среднего значения столбца точек:
#calculate mean value in points column
df.points.mean ()
18.25
Обратите внимание, что и на этот раз мы не получили никакой ошибки.
Дополнительные ресурсы
В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:
Как исправить в Python: объект ‘numpy.ndarray’ не вызывается
Как исправить: TypeError: объект ‘numpy.float64’ не вызывается
Как исправить: ошибка типа: ожидаемая строка или байтовый объект
The TypeError ‘DataFrame’ object is not callable occurs when you try to call a DataFrame by putting parenthesis ()
after it like a function. Only functions respond to function calls.
This tutorial will go through the error in detail and how to solve it with the help of code examples.
Table of contents
- TypeError: ‘DataFrame’ object is not callable
- Example
- Solution
- Summary
TypeError: ‘DataFrame’ object is not callable
Calling a function means the Python interpreter executes the code inside the function. In Python, we can only call functions. We can call functions by specifying the name of the function we want to use followed by a set of parentheses, for example, function_name()
. Let’s look at an example of a working function that returns a string.
# Declare function def simple_function(): print("Learning Python is fun!") # Call function simple_function()
Learning Python is fun!
We declare a function called simple_function
in the code, which prints a string. We can then call the function, and the Python interpreter executes the code inside simple_function()
.
DataFrame objects do not respond to a function call because they are not functions. If you try to call a DataFrame object as if it were a function, you will raise the TypeError: ‘DataFrame’ object is not callable.
We can check if an object is callable by passing it to the built-in callable()
method.
If the method returns True
, then the object is callable, otherwise, if it returns False
the object is not callable. Let’s look at testing the method with a DataFrame:
import pandas as pd df = pd.DataFrame({'values':[2, 4, 6, 8, 10, 12]}) print(callable(df))
False
The callable function returns false for a DataFrame, verifying that DataFrame objects are not callable.
Example
Let’s look at an example where we want to calculate the mean monthly amount of vegetables in kilograms sold by a farmer over the course of a year. First, we will look at the dataset.
Month,Amount 1,200 2,150 3,300 4,350 5,234 6,500 7,900 8,1000 9,959 10,888 11,3000 12,1500
The first column of the CSV is the month as a number and the second column is the number of vegetables sold in that month in kilograms. We will save the dataset as veg_sold.csv
.
Next, we will load the dataset into a DataFrame using pandas.
import pandas as pd df = pd.read_csv('veg_sold.csv') print(df)
Month Amount 0 1 200 1 2 150 2 3 300 3 4 350 4 5 234 5 6 500 6 7 900 7 8 1000 8 9 959 9 10 888 10 11 3000 11 12 1500
Next, we will try to calculate the mean amount sold by indexing the column name ‘Amount
‘ in the DataFrame and calling mean()
on the column.
mean_sold = df('Amount').mean() print(f'Mean sold over the year: {mean_sold}kg')
Let’s run the code to see what happens:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-8-5237331dba60> in <module> ----> 1 mean_sold = df('Amount').mean() 2 print(f'Mean sold over the year: {mean_sold}kg') TypeError: 'DataFrame' object is not callable
The error occurs because we tried to access the Amount column of the DataFrame using parentheses. Putting parentheses after the DataFrame object is interpreted by Python as a function call.
Solution
To solve this error, we can access the column of a DataFrame using square brackets. The resulting object will be a Series, which we can call the mean()
method on. Let’s look at the revised code:
mean_sold = df['Amount'].mean() print(f'Mean sold over the year: {mean_sold}kg')
Let’s run the code to get the result:
Mean sold over the year: 831.75kg
We can also call the mean method directly on the DataFrame. The resultant object will be a Series containing the mean of both columns. We can then access the mean of the ‘Amount
‘ column using square brackets. Let’s look at the revised code:
mean_cols = df.mean() print(f'Mean sold over the year: {mean_cols["Amount"]}kg')
Mean sold over the year: 831.75kg
Summary
Congratulations on reading to the end of this tutorial. The TypeError ‘DataFrame’ object is not callable occurs when you try to call a DataFrame as if it were a function. TypeErrors occur when you attempt to perform an illegal operation for a specific data type.
To solve this error, ensure that there are no parentheses after the DataFrames in your code. You can check if an object is a DataFrame by using the built-in type()
method.
For further reading on not callable TypeErrors, go to the articles:
- How to Solve Python TypeError: ‘tuple’ object is not callable.
- How to Solve Python TypeError: ‘bool’ object is not callable.
- How to Solve Python TypeError: ‘Series’ object is not callable.
To learn more about Python, specifically for data science and machine learning, go to the online courses page on Python.
Have fun and happy researching!
Are you encountering the ‘Dataframe object is not callable’ error while working with Pandas DataFrame? Don’t worry, you are not alone. This error occurs when you try to call a DataFrame object as if it were a function. This guide will walk you through the steps to resolve this error.
Table of Contents
- Understanding the ‘Dataframe Object is Not Callable’ Error
- Causes of the ‘Dataframe Object is Not Callable’ Error
- Resolving the ‘Dataframe Object is Not Callable’ Error
- FAQ
- Conclusion
- Related Links
Understanding the ‘Dataframe Object is Not Callable’ Error
The ‘Dataframe Object is Not Callable’ error usually appears when you try to call a DataFrame object as if it were a function. It is a common error encountered when working with Pandas DataFrame. This error message is accompanied by a traceback that shows where the error occurred in your code.
Causes of the ‘Dataframe Object is Not Callable’ Error
There are several reasons why you might encounter the ‘Dataframe Object is Not Callable’ error, some of which include:
- Using parenthesis instead of square brackets to access DataFrame columns.
- Overwriting a DataFrame object with a function or method of the same name.
- Calling an attribute of a DataFrame object as if it were a function.
- Using a variable name that conflicts with a DataFrame method or attribute.
Resolving the ‘Dataframe Object is Not Callable’ Error
To resolve the ‘Dataframe Object is Not Callable’ error, follow these steps:
- Check the syntax of your code to ensure that you are using square brackets instead of parenthesis to access DataFrame columns.
- Check that you have not overwritten a DataFrame object with a function or method of the same name.
- Ensure that you are not calling an attribute of a DataFrame object as if it were a function.
- Check that you are not using a variable name that conflicts with a DataFrame method or attribute.
FAQ
Q1. What is a DataFrame object in Pandas?
A DataFrame object is a two-dimensional table-like data structure that consists of rows and columns. It is the primary data structure used in Pandas for data analysis.
Q2. What does it mean when I get the ‘Dataframe Object is Not Callable’ error?
The ‘Dataframe Object is Not Callable’ error usually appears when you try to call a DataFrame object as if it were a function. This error occurs when you use parenthesis instead of square brackets to access DataFrame columns or when you overwrite a DataFrame object with a function or method of the same name.
Q3. How can I prevent the ‘Dataframe Object is Not Callable’ error from occurring?
To prevent the ‘Dataframe Object is Not Callable’ error from occurring, ensure that you are using square brackets instead of parenthesis to access DataFrame columns, and avoid overwriting a DataFrame object with a function or method of the same name.
Q4. What should I do if the ‘Dataframe Object is Not Callable’ error persists?
If the ‘Dataframe Object is Not Callable’ error persists, review your code and check for any syntax errors or variable name conflicts.
Q5. Is the ‘Dataframe Object is Not Callable’ error specific to Pandas?
Yes, the ‘Dataframe Object is Not Callable’ error is specific to Pandas.
Conclusion
The ‘Dataframe Object is Not Callable’ error is a common error encountered when working with Pandas DataFrame. It is caused by calling a DataFrame object as if it were a function. By following the steps outlined in this guide, you can easily resolve this error and continue with your data analysis tasks.
- Pandas DataFrame documentation
- Python documentation
One common error you may encounter when using pandas is:
TypeError: 'DataFrame' object is not callable
This error usually occurs when you attempt to perform some calculation on a variable in a pandas DataFrame by using round () brackets instead of square [ ] brackets.
The following example shows how to use this syntax in practice.
How to Reproduce the Error
Suppose we have the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'points': [18, 22, 19, 14, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print(df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7 H 28 4 12
Now suppose we attempt to calculate the mean value in the “points” column:
#attempt to calculate mean value in points column
df('points').mean()
TypeError: 'DataFrame' object is not callable
Since we used round () brackets, pandas thinks that we’re attempting to call the DataFrame as a function.
Since the DataFrame is not a function, we receive an error.
How to Fix the Error
The way to resolve this error is to simply use square [ ] brackets when accessing the points column instead round () brackets:
#calculate mean value in points column
df['points'].mean()
18.25
We’re able to calculate the mean of the points column (18.25) without receiving any error since we used squared brackets.
Also note that we could use the following dot notation to calculate the mean of the points column as well:
#calculate mean value in points column
df.points.mean()
18.25
Notice that we don’t receive any error this time either.
Additional Resources
The following tutorials explain how to fix other common errors in Python:
How to Fix in Python: ‘numpy.ndarray’ object is not callable
How to Fix: TypeError: ‘numpy.float64’ object is not callable
How to Fix: Typeerror: expected string or bytes-like object
Posted on Feb 09, 2023
If you work with the Python library pandas
, you might get the following error:
TypeError: 'DataFrame' object is not callable
This error occurs when you use parentheses ()
to access a pandas DataFrame column when you should use the square brackets []
.
For example, suppose you have a DataFrame object as follows:
import pandas as pd
df = pd.DataFrame({
"name": ["Nathan", "Jane", "John", "Lisa"],
"age": [29, 26, 28, 22],
"gold": [5000, 2200, 3200, 1000]
})
# Show the DataFrame
print(df)
Output:
name age gold
0 Nathan 29 5000
1 Jane 26 2200
2 John 28 3200
3 Lisa 22 1000
Next, want to display only the values in the “gold” column, so you specify it in the print()
function:
But you’ve wrongly used the round brackets ()
when accessing the column! This causes Python to respond with:
Traceback (most recent call last):
File "main.py", line 10, in <module>
print( df('gold') )
^^^^^^^^^^
TypeError: 'DataFrame' object is not callable
In Python, square brackets are used to call a function, and it’s no different when you’re using the pandas library.
A DataFrame
is an object, so you receive an error when calling it like a function.
How to fix this error
To fix this error, you just need to replace the round brackets ()
with square brackets []
when accessing a DataFrame column.
Here’s an example:
Output:
0 5000
1 2200
2 3200
3 1000
Name: gold, dtype: int64
Beside using square brackets []
, you can also use the dot notation .
to access a DataFrame column:
Now the error is resolved!
When using pandas, you can use the round brackets ()
when you need to call a function.
For example, suppose you need to sum the values in the “gold” column. Here’s how you call the sum()
function:
total_gold = df['gold'].sum()
# or
total_gold = df.gold.sum()
print(total_gold) # 11400
I hope this tutorial gives you a clear understanding of why the error occurs and how to fix it. See you again! 👋