Ошибка dataframe object is not callable

Написала код для сбора информации с сайта, обернула его в функцию:

def Table1(u):
#////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# table 1 CA ---------------------------------------------------------------------------------------------------------------------------------
# C - Chairman / M - Members
# A - actual / H - historical
    Date = driver.find_element_by_xpath(DateLinls.iloc[u,0])
    trsCA = driver.find_elements_by_xpath('//div/table/tbody/tr[1]/td/div/table/tbody/tr[2]/td/div/table/tbody/tr') # used for Person name PN and previous jobs PJ
    aCA = "//div/table/tbody/tr[1]/td/div/table/tbody/tr[2]/td/div/table/tbody/tr[" # used for Person name PN and previous jobs PJ

# Person name variable +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    bCAPN = "]/td[1]/div/a"
    PNCAl1 = []
    for i in range(1,len(trsCA)+1):
        result = aCA + str(i) + bCAPN
        PNCAr = driver.find_element_by_xpath(result)
        PNCAl1.append(PNCAr.text)
        PNCA = pd.DataFrame(PNCAl1)
        #print(PNCA)
# Title ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++    
    
    CATr = driver.find_element_by_xpath('//div/table/tbody/tr[1]/td/div/table/tbody/tr[1]/td/h3')

# Year of birth +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    bCAY = ']/td[1]/div/div[1]'
    CAYl = []
    for i in range(1,len(trsCA)+1):
        result = aCA + str(i) + bCAY 
        CAYr = driver.find_element_by_xpath(result)
        CAYl.append(CAYr.text)
        CAY = pd.DataFrame(CAYl)
# Education +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    bCAE = ']/td[1]/div/div[2]'
    CAEl = []
    for i in range(1,len(trsCA)+1):
        result = aCA + str(i) + bCAE 
        CAEr = driver.find_element_by_xpath(result)
        CAEl.append(CAEr.text)
        CAE = pd.DataFrame(CAEl)

# Previous Jobs and MAIN CODE =================================================================================================================
    
    bPJ = ']/td[3]/div'
    PJCAl =[]
    for i in range(1,len(trsCA)+1):
        result = aCA + str(i) + bPJ
        PJCAl.append(result)
        PJCA = pd.DataFrame(PJCAl)
    PJCAl = []
    PNCAl = []
    DPl = []
    CAJl = [] # JOBS 
    for i in range(0,len(trsCA)):
        trsPJCA1 = driver.find_elements_by_xpath(PJCA.iloc[i,0]) # this is a number of div
        DPl.append(len(trsPJCA1))
        DP = pd.DataFrame(DPl)
        NumbersOfNamesCA = numpy.array(DP.iloc[:,0])
        a3 = str(PJCA.iloc[i,0]) #this is begining of link 
        for j in range(1,len(trsPJCA1)+1): # continue taking previous jobs WORKS
            bCAJ1 = ']'
            bCAJ2 = '['
            result = a3 + bCAJ2 + str(j) + bCAJ1
            CAJr = driver.find_element_by_xpath(result)
            print(CAJr.text)
            CAJl.append(CAJr.text)
            CAJF = pd.DataFrame(CAJl)
# code which print/take names depends on how many time they need to be printed WORKS

    PNCAl1 = [] # NAME
    for g in range(0,len(trsCA)):
        a = int(g)
        for k in range(0,NumbersOfNamesCA[a]):
            if NumbersOfNamesCA[a] == 0:
                PNCAl1.append("-")
                PNCAF = pd.DataFrame(PNCAl1)
            else:
                PNCAl1.append(PNCA.iloc[g,0])
                PNCAF = pd.DataFrame(PNCAl1)

    CAYl1 = [] # YER OF BIRTH
    for g in range(0,len(trsCA)):
        a = int(g)
        for k in range(0,NumbersOfNamesCA[a]):
            if NumbersOfNamesCA[a] == 0:
                CAYl1.append("-")
                CAYF = pd.DataFrame(CAYl1)
            else:
                CAYl1.append(CAY.iloc[g,0])
                CAYF = pd.DataFrame(CAYl1)

    CAEl1 = [] # EDUCATION
    for g in range(0,len(trsCA)):
        a = int(g)
        for k in range(0,NumbersOfNamesCA[a]):
            if NumbersOfNamesCA[a] == 0:
                CAEl1.append("-")
                CAEF = pd.DataFrame(CAEl1)
            else:
                CAEl1.append(CAE.iloc[g,0])
                CAEF = pd.DataFrame(CAEl1)

    CATl = [] # Title
    for i in range(0,len(CAJF)):
        CATl.append(CATr.text)
        CAT = pd.DataFrame(CATl)

    CADl = [] # Date
    for i in range(0,len(CAJF)):
        CADl.append(Date.text)
        CAD = pd.DataFrame(CADl)

    CAIDl = [] # ID
    for i in range(0,len(CAJF)):
        CAIDl.append(IDd.iloc[u,0]) # 3 ingecates position of INN from Dataframe which we've created before in mine loop should be replased by i/j/wharever
        CAIDf = pd.DataFrame(CAIDl)
# concat to 1st table Database

    #FirstTable = pd.DataFrame(columns=(['ID', 'Title', 'Date', 'Name', 'YearOfBirth', 'Education', 'Jobs']))
    FirstTable = pd.concat([CAIDf, CAT, CAD, PNCAF, CAYF, CAEF, CAJF], axis=1)
    return FirstTable

Таких функций несколько. Хочу поместить их в цикл for, чтобы пройтись по списку страниц сайта.

Пока для теста это выглядит так:

if __name__ == '__main__':   
    u = 1
    driver.get(MyLinks.iloc[u,0])
    Table1 = Table1(u)
    #Table2 = Table2(u)
    #Table3 = Table3(u)
    #Table4 = Table4(u)

Проблема в том, что когда выделяю просто строку, например Table1 = Table1(u) и нажимаю F9, все прекрасно работает. Но когда выделяю весь код, выдает ошибку TypeError: 'DataFrame' object is not callable .

Пробовала использовать return(FirstTable) вместо return FirstTable все равно не работает.

The error traceback

Выдает следующее:

Traceback (most recent call last):

  File "<ipython-input-10-844b48fac0c3>", line 5, in <module>
    Table2 = Table2(u)

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

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!

Привет!

Когда я итерируюсь по датафрейму, то почаю следующую ошибку:
TypeError: 'DataFrame' object is not callable

В коде я проверя введенно ли цифровое значение в ячейку. Пустая ячейка допускается

def read_file_to_df(file):
    data = pd.read_excel(file)

    for index, row in data.iterrows():
        if row["Оценка"] is not None and type(row["Оценка"]) != float:
            raise ValueError(_("Упс... Строка {} столбца Оценка должна содержать число или быть пустой!").format(index + 2))

    return data

Подскажите, в чем причина ошибки?


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

Возможно, вам также будет интересно:

  • Ошибка data type mismatch
  • Ошибка data truncated for column at row 1
  • Ошибка data folder not found как исправить
  • Ошибка dasd сервер ibm
  • Ошибка daf 105 p0087

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии