为什么 numpy.ndarray 是对象在我的简单 for python 循环中不可调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37222989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:04:36  来源:igfitidea点击:

why numpy.ndarray is object is not callable in my simple for python loop

pythonnumpy

提问by mee mee

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:

我的计算只是对每一行求和,即 1+3、2+4、3+5 和 2+0。我正在使用以下代码:

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.

但是我收到一个错误说numpy.ndarray object is not callable. 为什么会发生这种情况?我怎样才能做这个简单的计算?谢谢。

回答by Vadiraja K

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

错误 TypeError: 'numpy.ndarray' object is not callable 意味着您试图将 numpy 数组作为函数调用。

Use

Z=XY[0]+XY[1]

Instead of

代替

Z=XY(i,0)+XY(i,1)

回答by tfv

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)

回答by abunickabhi

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

避免 for 循环for XY in xy:而是阅读如何索引和处理 numpy 数组。

Numpy Indexing

Numpy 索引

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.

如果您正在处理矩阵,也尽量避免使用 .txt 文件。尝试使用 .csv 或 .npy 文件,并使用 Pandas 数据框架加载它们只是为了清楚起见。

回答by Bigyan Karki

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.

有时,当函数名和存储函数返回的变量名相同时,会显示错误。刚刚发生在我身上。