类型错误:迭代 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
TypeError: iteration over a 0-d array Python
提问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))
...
回答by jpp
The problem is np.array
does not take an iterator, you need convert to list
first, 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.array
documentation, 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.fromiter
and remember to supply dtype
, e.g. dtype=float
.
或者,使用numpy.fromiter
并记住提供dtype
,例如dtype=float
。