Python ошибка dataframe object is not callable

  • Редакция Кодкампа


читать 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!


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

This article demonstrates how to debug the “TypeError: ‘DataFrame’ object is not callable” in the Python programming language.

Table of contents:

You’re here for the answer, so let’s get straight to the programming part!

Example Data & Libraries

We first have to import the pandas library:

import pandas as pd                              # Load pandas

As a next step, we also need to create some data that we can use in the exemplifying code later on.

data = pd.DataFrame({'x1':range(70, 64, - 1),    # Create pandas DataFrame
                     'x2':['a', 'b', 'c', 'a', 'b', 'c'],
                     'x3':[1, 7, 5, 9, 1, 5]})
print(data)                                      # Print pandas DataFrame
#    x1 x2  x3
# 0  70  a   1
# 1  69  b   7
# 2  68  c   5
# 3  67  a   9
# 4  66  b   1
# 5  65  c   5

Example 1: Reproduce the TypeError: ‘DataFrame’ object is not callable

In Example 1, I’ll explain how to replicate the “TypeError: ‘DataFrame’ object is not callable” in the Python programming language.

Let’s assume that we want to calculate the variance of the column x3. Then, we might try to use the Python code below:

data('x3').var()                                 # Code leads to error
# TypeError: 'DataFrame' object is not callable

Unfortunately, the Python console returns the error message “TypeError: ‘DataFrame’ object is not callable” after executing the previous Python syntax.

The reason for this is that we have tried to use round parentheses to select the variable x3 (i.e. data(‘x3’)).

Let’s solve this problem!

Example 2: Debug the TypeError: ‘DataFrame’ object is not callable

In Example 2, I’ll show how to fix the “TypeError: ‘DataFrame’ object is not callable”.

To achieve this, we have to use square brackets instead of round parentheses to extract our pandas DataFrame column (i.e. data[‘x3’]).

Consider the syntax below:

data['x3'].var()                                 # Code works fine
# Out[13]: 10.266666666666666

The previous Python code has returned a proper result, i.e. the variance of the column x3 is equal to 10.266666666666666. No error messages are returned anymore.

Video, Further Resources & Summary

Do you need more explanations on the Python codes of this tutorial? Then you may want to watch the following video on my YouTube channel. In the video, I’m explaining the Python programming code of this article in a live session:

Furthermore, you may read the related articles on my website. A selection of articles is listed here:

  • How to Use the pandas Library in Python
  • Select Multiple Columns of Pandas DataFrame in Python
  • Select Columns of pandas DataFrame by Index
  • Extract First & Last N Columns from pandas DataFrame
  • All Python Programming Tutorials

At this point you should have learned how to handle the “TypeError: ‘DataFrame’ object is not callable” in the Python programming language. Let me know in the comments, in case you have additional questions. In addition, don’t forget to subscribe to my email newsletter to receive updates on new tutorials.

Generally, this typeerror dataframe object is not a callable error that occurs when we use dataframe as a function, with or without arguments. In this article, we will see this error with an example. Firstly we will understand the root cause. After it, We will also explore ways to fix the same.

In order to justify this scenario, There is a prerequisite for creating a pandas dataframe. We will try to keep the rows minimal in order to keep this article and topic simple.

import pandas as pd
data = {
    'Name' : ['SAM', 'Aish', 'Mohan', 'Shivangi'],
    'Exp' : [23, 21, 22, 21]
       }

df = pd.DataFrame(data)
df

Scenario 1: Calling dataframe as function without arguments-

Now after creating this dataframe. If we run the below syntax we will get the dataframe object is not a callable error. Here in the above example dataframe, we will directly call as a method in the place of any attribute. Let’s see how –

typeerror dataframe object is not callable error

typeerror dataframe object is not callable error

Scenario 2: Calling dataframe as function with arguments-

Nothing two different from above but suppose you want to check the variance of any dataframe columns. You can use var() function for the same. But if you do it syntactically wrong, Please refer to the below image.

dataframe as function - incorrect way to call

dataframe as function – incorrect way to call

Solution-

This is pretty state to fix this issue. The Path is very simple, we should correctly call the function. Let’s take the above example where we call df(“var”) function. The correct way is

dataframe var() function

dataframe var() function

Here we are calling the attribute of dataframe function. This will compute the variance of the numerical column of dataframe.

Specially Spark dataframe, when we call the same it will generate the same error. Basically, it is the same with each object when we call it a function instead of the object attribute. The Typeerror is one of the most common errors in the Python world. Hope now you can fix the same.

Thanks 

Data Science Learner Team 

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Понравилась статья? Поделить с друзьями:
  • Qsx15 cummins коды ошибок
  • Python ошибка времени исполнения
  • Python ошибка str object is not callable
  • Qsp ошибка 119
  • Python ошибка runtime error