简体   繁体   English

如何在Python中根据另一个数组中的值提取一个数组中的数据

[英]How to extract data in one array according to the values in another array in Python

I have two arrays like: 我有两个像这样的数组:

a = np.array([[0.3, 0.4, 0.3],[0.6, 0.2, 0.2],[0.1, 0.2, 0.7]]) 
b = np.array([[1,2,3], [4,5,6], [7,8,9]])

I hope could get the values in b according to the position of the max value in each row in a, the expected output should be: 我希望可以根据a中每一行中最大值的位置获取b中的值,预期输出应为:

[2, 4, 9]

Thanks. 谢谢。

How about: 怎么样:

>>> a = np.array([[0.3, 0.4, 0.3],[0.6, 0.2, 0.2],[0.1, 0.2, 0.7]])
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> b[np.arange(len(b)),a.argmax(axis=1)]
array([2, 4, 9])

Although you should double-check the axis; 尽管您应该仔细检查轴; I always get those backwards. 我总是把那些倒退。

If you had this as a 2-d python list: 如果您将其作为二维Python列表:

answer = []
for r,row in zip(b,a):
    big = max(enumerate(row), key=operator.itemgetter(1))
    answer.append(r[big[0]])

Of course, you could do this as a one-liner: 当然,您可以单线执行此操作:

answer = [r[max(enumerate(row), key=operator.itemgetter(1))[0]] for r,row in zip(b,a)]
def b_from_a(a,b):
    if len(a) != len(b):
        raise ValueError("Both lists should be the same length")
    for i,element in enumerate(a):
        if len(a[i]) != len(b[i]):
            raise ValueError("The lists in element {} are not of equal length".format(i))
        i_of_max = a.index(max(a))
        yield b[i][i_of_max]

This is in pure python. 这是纯Python语言。 I don't do any work with NumPy so although I'm sure there's a better bit of code that will get you where you want to go, this should work. 我不使用NumPy进行任何工作,因此尽管我确定有更好的代码可以使您到达想要的位置,但这应该可以工作。

try this: 尝试这个:

result = np.zeros(len(a));
for i in range(len(a)):
    result[0] = b[i][a[i].argmax()];

print(result)

(as long as np stands for NumPy) (只要np代表NumPy)

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

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