27

I loaded a text file containing a two column matrix (e.g. below)

[ 1   3
  2   4
  3   5 
  2   0]

My calculation is just to sum each row i.e. 1+3, 2+4, 3+5 and 2+0. I am using the below code:

data=np.loadtxt(fname="textfile.txt")## to load the above two column
xy= data
for XY in xy:
   i=0  
   Z=XY(i,0)+XY(i,1)
   i=i+1      
   print (Z)

But I received an error saying numpy.ndarray object is not callable. Why does this happen? How can I do this simple calculation? Thanks.

6 Answers 6

53

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function.

Use

Z=XY[0]+XY[1]

Instead of

Z=XY(i,0)+XY(i,1)
1
  • 1
    @tfv gave a cleaner way to do it. data.sum(axis=1) is again a numpy array which you can access with array[i].
    – Vadiraja K
    May 14, 2016 at 5:46
13

Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.

0
9

Avoid loops. What you want to do is:

import numpy as np
data=np.loadtxt(fname="data.txt")## to load the above two column
print data
print data.sum(axis=1)
2

Avoid the for loopfor XY in xy: Instead read up how the numpy arrays are indexed and handled.

Numpy Indexing

Also try and avoid .txt files if you are dealing with matrices. Try to use .csv or .npy files, and use Pandas dataframework to load them just for clarity.

0

Not for the example asked above but sometimes this error happens because you forget to specify brackets [] instead of parenthesis for your numpy.ndarray. Such as writing arr(x,y) in a for loop that explores x and y in arr instead of its correct form: arr[x,y].

0

I had variable named "open" so when i had been trying to use function "open" program had been calling the "open" variable instead of "open" function. So i found two solutions:

  1. To rename variable
  2. To delete variable before calling "open" function

Not the answer you're looking for? Browse other questions tagged or ask your own question.