Saturday, November 6, 2021

ItsMyCode: [Solved] NumPy.ndarray object is Not Callable Python

ItsMyCode |

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.

NumPy.ndarray object is Not Callable Error

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.

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 a NumPy.ndarray 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.

# 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))

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.

The post [Solved] NumPy.ndarray object is Not Callable Python appeared first on ItsMyCode.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...