简体   繁体   中英

TypeError: iteration over a 0-d array Python

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 "

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: 在此处输入图片说明

The problem is np.array does not take an iterator, you need convert to list first, as below:

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:

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 , eg dtype=float .

It is possible to load a 0-d numpy array with arr1 = np.load(..., allow_pickle=True) . To access the item stored as being a np.array, use:

arr1.item()

For instance, if the type stored is a dict d1 = {'item1':42, 'item2':np.array(1,3)} we can get the value as such: v1 = arr1.item()['item2'] .

Important: Loading with allow_pickle=True is brings security risks and is not recommended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM