从元组数组中提取所需的索引

时间:2015-01-01 21:40:24

标签: python arrays numpy

import numpy as np
from scipy import signal

y = np.array([[2, 1, 2, 3, 2, 0, 1, 0],
             [2, 1, 2, 3, 2, 0, 1, 0]])

maximas = signal.argrelmax(y, axis=1)

print maximas

(array([0, 0, 1, 1], dtype=int64), array([3, 6, 3, 6], dtype=int64))

最大值产生元组索引:(0,3)和(0,6)是第一行[2,1,2,3,2,0,1,0]; (1,6)和(1,6)用于另一行[2,1,2,3,2,0,1,0]。

以下打印所有结果,但我想只提取两行的第一个最大值,即[3,3]使用元组。所以,我需要的元组是(0,3)和(1,3)。

如何从元组数组中提取它们,即' maximas'?

>>> print y[kk]
[3 1 3 1]

2 个答案:

答案 0 :(得分:2)

鉴于元组maximas,这里有一种可能的NumPy方式:

>>> a = np.column_stack(maximas)
>>> a[np.unique(a[:,0], return_index=True)[1]]
array([[0, 3],
       [1, 3]], dtype=int64)

这会将signal.argrelmax返回的坐标列表堆叠到数组a中。 return_index np.unique参数用于查找每个行号的第一个索引。然后,我们可以使用这些第一个索引从a检索相关的行。

这将返回一个数组,但您可以将其转换为包含tolist()的列表列表。

要返回每行中最大值的第一列索引,您只需要从np.unique获取maximas[0]返回的索引,并使用它们来索引maximas[1]。在一行中,它是这样的:

>>> maximas[1][np.unique(maximas[0], return_index=True)[1]]
array([3, 3], dtype=int64)

要从y的每一行检索相应的值,您可以使用np.choose

>>> cols = maximas[1][np.unique(maximas[0], return_index=True)[1]]
>>> np.choose(cols, y.T)
array([3, 3])

答案 1 :(得分:1)

嗯,纯Python方法将使用itertools.groupby(行的索引上的组)和列表理解:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> [max(g, key=lambda x: y[x])
                             for k, g in groupby(zip(*maximas), itemgetter(0))]
[(0, 3), (1, 3)]