多数组索引

2024-04-20 09:50:11 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有四个列表(实际上我还有更多,从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'...]

Tags: csvthenumpy列表foobarcover数组
1条回答
网友
1楼 · 发布于 2024-04-20 09:50:11

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

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')

相关问题 更多 >