类型错误:迭代 0 维数组 Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48643256/
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 18:47:37  来源:igfitidea点击:

TypeError: iteration over a 0-d array Python

pythonarraysnumpyiteratortypeerror

提问by Anna Huang

I am trying to write a very basic nearest neighbor calculation. I basically want to see what t looks like but I got this type error. When I asked the funciton to return just t it said "". When I asked it to turn to list it threw "TypeError: iteration over a 0-d array Python "

我正在尝试编写一个非常基本的最近邻计算。我基本上想看看 t 是什么样子,但我遇到了这种类型的错误。当我要求功能返回时,它说“”。当我要求它转至列表时,它抛出了“TypeError:在 0-d 数组 Python 上迭代”

How do I fix this please?

我该如何解决这个问题?

...

t = np.array(map(lambda v:
             map(lambda w: distance(v, w, L), x_train.values),
             x_test.values)) 

...

Full trace: enter image description here

完整跟踪: 在此处输入图片说明

回答by jpp

The problem is np.arraydoes not take an iterator, you need convert to listfirst, as below:

问题是np.array不带迭代器,需要先转换为list,如下:

t = np.array(list(map(lambda v: map(lambda w: distance(v, w, L),
                      x_train.values), x_test.values)))

As per numpy.arraydocumentation, the required parameter must be:

根据numpy.array文档,所需的参数必须是:

An array, any object exposing the array interface, an object whose array method returns an array, or any (nested) sequence.

一个数组,任何暴露数组接口的对象,一个数组方法返回一个数组的对象,或任何(嵌套)序列。

Alternatively, use numpy.fromiterand remember to supply dtype, e.g. dtype=float.

或者,使用numpy.fromiter并记住提供dtype,例如dtype=float