python - 索引多个数组

标签 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'...]

最佳答案

您可以使用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')

关于python - 索引多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42729021/

相关文章:

python正则表达式匹配返回完整句子

python - 扩展/放大 numpy 数组

swift - Swift中链接列表的自定义索引

Java:创建一个以字母字符为索引的数组

python - 在 mypy 中记录处理程序名称注释

python - Python中的数组操作

Python - 字典中函数的错误分配

python - 第一次出现大于 numpy 数组中给定值的值

python - 列表未对齐?

python - 在 Pandas 中选择感兴趣的行之前和之后的行