索引多个数组

时间:2017-03-10 22:49:03

标签: python numpy indexing

鉴于我有四个列表(实际上我还有更多列表,从CSV读入为numpy数组),这样:

a = [54,35,67...]
b = [45,21,87...]
c = [32,58,52...]
d = [4,78,43...]
# In reality I have plant % cover surveyed at a location

和四个列表如:

A = ['foo', 'bar', 'ham'...]
B = ['eggs', 'spam', 'bar'...]
C = ['ham', 'eggs', 'foo'...]
D = ['eggs', 'spam', 'bar'...]
# These are plant species

我可以使用以下方法找到a,b,c和d的最大值:

max = [a, b, c, d].max(axis=0)
# The max plant % cover between a, b, c and d on the 0 axis

得到:

max = [54, 78, 87...]
# the plant species that accompanies the max plant % cover

但是我现在如何获得相应的文本值,所以我的输出如下:

Text = ['foo', 'spam', 'bar'...]

1 个答案:

答案 0 :(得分:1)

您可以使用argmax获取最大值的索引,并使用advanced indexing从names数组中获取名称:

import numpy as np

names = np.array([A, B, C, D])
values = np.array([a, b, c, d])

# use argmax to find out the index of the max values
index_max = values.argmax(0)
​
# use index to pick up corresponding names using advance indexing
names[index_max, np.arange(names.shape[1])]

# array(['foo', 'spam', 'bar'], 
#       dtype='<U4')