Numpy ndarray object is not callable ошибка

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you’d like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

In Python, the array will be accessed using an indexing method. Similarly, the NumPy array also needs to be accessed through the indexing method. In this article, we will look at how to fix the NumPy.ndarray object is Not Callable error and what causes this error in the first place.

The object is not callable error occurs when you try to access the NumPy array as a function using the round brackets () instead of square brackets [] to retrieve the array elements.

In Python, the round brackets or parenthesis () denotes a function call, whereas the square bracket [] denotes indexing. Hence, when using round brackets while accessing the array, Python cannot handle it and throws an error.

An Example

Let’s take a simple example, we have an array of fruits, and we are trying to access the last element of an array and print the fruit.

# NumPy.ndarray object is Not Callable Error
import numpy as np

fruits = np.array(["Apple","Grapes","WaterMelon","Orange","Kiwi"])
last_fruit = fruits(-1)

print("The last fruit in the array is {} ".format(last_fruit))

When we run the code, we get an error, as shown below.

Traceback (most recent call last):
  File "c:/Projects/Tryouts/main.py", line 5, in <module>
    last_fruit = fruits(-1)
TypeError: 'numpy.ndarray' object is not callable

Solution NumPy.ndarray object is Not Callable Error

In the above example, we tried to access the last item of the array element using the round brackets (), and we got an object is not Callable Error.

fruits = np.array(["Apple","Grapes","WaterMelon","Orange","Kiwi"])
last_fruit = fruits(-1)

We can fix this code by replacing the round brackets with square brackets, as shown below.

import numpy as np

fruits = np.array(["Apple","Grapes","WaterMelon","Orange","Kiwi"])
last_fruit = fruits[-1]

print("The last fruit in the array is {} ".format(last_fruit))

Output

The last fruit in the array is Kiwi 

Conclusion

The ‘numpy.ndarray’ object is not callable error occurs when you try to access the NumPy array as a function using the round brackets () instead of square brackets [] to retrieve the array elements. To fix this issue, use an array indexer with square brackets to access the elements of the array.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

In all programming languages, array data structures are used to store multiple homogeneous elements at the same time. In Python, an open-source library Numpy is used to create arrays. The elements of an array in Python can be accessed using the index number. However, sometimes, the “’numpy.ndarray’ object is not callable” error occurs in Python programs while accessing the arrays.

This post will deliver a thorough guide on various reasons and solutions regarding the “TypeError: ‘numpy.ndarray’ object is not callable” in Python. In this Python blog post, the following aspects are discussed in detail:

  • Reason 1: Calling Array as a Function
  • Solution: Use Square Bracket While Accessing
  • Reason 2: Similar Function and Variable Name
  • Solution: Rename Function or Variable

So, let’s get started!

Reason 1: Calling Array as a Function

One major reason for this error in Python programs is accessing array elements using parentheses instead of square brackets.

In the above snippet, the “TypeError: ndarray object is not callable” occurs when the array element is accessed using parentheses.

Solution: Use Square Bracket While Accessing

To resolve this error, use square brackets instead of parentheses while accessing the array element in the Python program.

Code:

import numpy as np

array_val = np.array([11, 22, 33, 44])

print(array_val[1])

In the above code, the “NumPy” library is imported as “np”, and the “np.array()” function is used to create an array. The variable of the array used a square bracket with an integer value (index number) to access the element of the array, such as “array_val[1]”.

Output:

The above output shows that replacing the parenthesis with the square brackets resolves the stated error.

Reason 2: Similar Function and Variable Name

Another common reason for this error is using the same name for a function and variable in the program.

The output snippet shows that a TypeError occurs when a function and a variable are created with the same name.

Note: If the variable is initialized before the function with the same name, the TypeError will not appear in the output. Because in such a case, the Python interpreter will ignore the variable and execute the value of the function.

Solution: Rename Function or Variable

To resolve this error, either the function’s name or the variable’s name must be altered in the program.

Code:

import numpy as np

def sample():
    x = np.array([55,66,77,88])
    print(x)

sample_1 = np.array([23, 44, 32])

sample()

In the above code, a function, and a variable are initialized with the different names. The function is accessed at the end of the program using the function’s name followed by parentheses, such as sample().

Output:

The above snippet shows the value of the array initialized in the function.

That’s it from this Python guide!

Conclusion

The “numpy.ndarray object is not callable” error occurs when a user tries to call an array as a function or uses the same name for a function and variable. To rectify this error remove the parentheses and use a square bracket while accessing the array element. Rename the function or variable when they are found with the same name in the Python program. This article presented a detailed guide on various causes and solutions of the “numpy.ndarray object is not callable” error in Python.


One common error you may encounter when using NumPy in Python is:

TypeError: 'numpy.ndarray' object is not callable

This error usually occurs when you attempt to call a NumPy array as a function 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 NumPy array:

import numpy as np

#create NumPy array
x = np.array([2, 4, 4, 5, 9, 12, 14, 17, 18, 20, 22, 25])

Now suppose we attempt to access the first element in the array:

#attempt to access the first element in the array
x(0)

TypeError: 'numpy.ndarray' object is not callable

Since we used round () brackets Python thinks we’re attempting to call the NumPy array x as a function.

Since x 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 elements of the NumPy array instead of round () brackets:

#access the first element in the array
x[0]

2

The first element in the array (2) is shown and we don’t receive any error because we used square [ ] brackets.

Also note that we can access multiple elements of the array at once as long as we use square [ ] brackets:

#find sum of first three elements in array
x[0] + x[1] + x[2]

10

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix: ValueError: Index contains duplicate entries, cannot reshape
How to Fix: Typeerror: expected string or bytes-like object
How to Fix: TypeError: ‘numpy.float64’ object is not callable

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


читать 1 мин


Одна распространенная ошибка, с которой вы можете столкнуться при использовании NumPy в Python:

TypeError : 'numpy.ndarray' object is not callable

Эта ошибка обычно возникает, когда вы пытаетесь вызвать массив NumPy как функцию, используя круглые скобки () вместо квадратных скобок [ ] .

В следующем примере показано, как использовать этот синтаксис на практике.

Как воспроизвести ошибку

Предположим, у нас есть следующий массив NumPy:

import numpy as np

#create NumPy array
x = np.array([2, 4, 4, 5, 9, 12, 14, 17, 18, 20, 22, 25])

Теперь предположим, что мы пытаемся получить доступ к первому элементу массива:

#attempt to access the first element in the array
x(0)

TypeError : 'numpy.ndarray' object is not callable

Поскольку мы использовали круглые () скобки, Python думает, что мы пытаемся вызвать массив NumPy x как функцию.

Поскольку x не является функцией, мы получаем ошибку.

Как исправить ошибку

Способ устранения этой ошибки — просто использовать квадратные [] скобки при доступе к элементам массива NumPy вместо круглых () скобок:

#access the first element in the array
x[0]

2

Показан первый элемент в массиве (2), и мы не получаем никакой ошибки, потому что мы использовали квадратные скобки [ ] .

Также обратите внимание, что мы можем получить доступ к нескольким элементам массива одновременно, если используем квадратные скобки [] :

#find sum of first three elements in array
x[0] + x[1] + x[2]

10

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить: ValueError: Индекс содержит повторяющиеся записи, не может изменить форму
Как исправить: ошибка типа: ожидаемая строка или байтовый объект
Как исправить: TypeError: объект ‘numpy.float64’ не вызывается

Понравилась статья? Поделить с друзьями:
  • Ntdsutil ошибка при синтаксическом разборе ввода неправильный синтаксис
  • Numplate light ошибка bmw
  • Ntdll dll ошибка windows 7 x64
  • Num ошибка раздачи не найдены
  • Ntdll dll ошибка windows 10 скачать