简体   繁体   English

处理一个Numpy数组的拐角案例以进行迭代

[英]Handling corner case of one Numpy array to iterate over

I have a list of Numpy arrays with the same shape (but not necessarily the same dtype ) and I want to iterate over the elements of all the arrays at the same time. 我有一个具有相同形状的Numpy数组列表(但不一定是相同的dtype ),并且我想同时遍历所有数组的元素。 For instance, if the arrays are: 例如,如果数组是:

>>> a = np.array([[1,2,3], [4,5,6]])
>>> b = np.array([['one','two','three'],['four','five','six']])

I want the iteration over [a, b] to yield 我希望对[a, b]的迭代产生

[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five'), (6, 'six')]

I have found that numpy.nditer does almost what I need. 我发现numpy.nditer 几乎 可以满足我的需求。 This works: 这有效:

>>> for x, y in np.nditer([a, b]):
...     print('{} {}'.format(x, y))
1 one
2 two
3 three
4 four
5 five
6 six

Note that the iterator yields tuples of scalars: 请注意,迭代器产生标量的元组:

>>> next(np.nditer([a, b]))
(array(1), array('one', dtype='<U5'))

However, in the corner case of a list containing one array, np.nditer directly yields the array elements: 但是,在列表包含一个数组的np.nditer情况下, np.nditer直接产生数组元素:

>>> next(np.nditer([a]))
array(1)

I need it to yield a tuple with one element because I am unpacking the iterated values in the arguments of a function within the loop. 我需要它来生成具有一个元素的元组,因为我要在循环内的函数参数中解压缩迭代值。

How do I convince np.nditer to yield a one-element tuple when iterating over a list of one array? 在遍历一个数组的列表时,如何说服np.nditer生成一个单元素元组?

One workaround would be np.atleast_1D : 一种解决方法是np.atleast_1D

a = sum(np.ogrid[2:4, 3:5])
b = 2*a
for z in map(np.atleast_1d, np.nditer([a, b])):
    print(np.arange(*z))

#[5 6 7 8 9]
#[ 6  7  8  9 10 11]
#[ 6  7  8  9 10 11]
#[ 7  8  9 10 11 12 13]

for z in map(np.atleast_1d, np.nditer([a])):
    print(np.arange(*z))

#[0 1 2 3 4]
#[0 1 2 3 4 5]
#[0 1 2 3 4 5]
#[0 1 2 3 4 5 6]

Note that this unpacks the 0D arrays nditer returns into proper scalars. 请注意,这nditer返回的0D数组解压缩为适当的标量。 Also, it yields arrays, not tuples but as you just want to splat them to a function it shouldn't matter. 同样,它产生数组,而不是元组,但是只要您将其splat到一个函数上就没关系。

That goes against the behaviour of nditer . 这违背了nditer的行为。

Maybe you can always supply an array of None so that you always get a tuple? 也许您总是可以提供None数组,以便始终获得一个元组? You have to handle the None in the function though. 但是,您必须在函数中处理None。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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