简体   繁体   English

如何使用两个不同的 arrays 处理不同的索引

[英]How to handle different indices with two different arrays

I have two arrays y=[0,1,1], x=[0,0,4,10,5] and a Index-array with integers that has the indices of the non-zero entrys from x I_x=[2,3,4] .我有两个 arrays y=[0,1,1], x=[0,0,4,10,5]和一个索引数组,其中包含来自 x I_x=[2,3,4]的非零条目的索引I_x=[2,3,4]

And idealy I would want something like y[2]=0, y[3]=1, y[4]=1理想情况下,我想要y[2]=0, y[3]=1, y[4]=1

Is there any way to do that for the general case.对于一般情况,有什么办法可以做到这一点。

I'm happy to answer further questions because I don't think this question is asked well enough.我很乐意回答更多问题,因为我认为这个问题问得不够好。

edit:编辑:

def function(x,y):
    solution = 0
    for i in I:
        solution = x[i] + y[i]
    return solution

This is an example what I want to do, the problem is i is from I so y would be out of bounds, what I want to know is there any way to solve this problem.这是我想做的一个例子,问题是i来自我,所以 y 会越界,我想知道有什么办法可以解决这个问题。

Your question is still a bit unclear, but I think you are trying to produce an array which contains the sum of the nonzero elements in x with the elements in y in those positions, and you are trying to adjust it so that I x will not be out of bounds for y .您的问题仍然有点不清楚,但我认为您正在尝试生成一个数组,其中包含x中的非零元素与y中的元素在这些位置的总和,并且您正在尝试调整它,以便I x不会超出y的范围。 The script below does just that:下面的脚本就是这样做的:

import numpy as np

def uneven_add(a, b):
    return a[np.nonzero(a)] + np.hstack((b, np.zeros((a.size - b.size))))[np.nonzero(a)]

if __name__ == '__main__':
    x = np.array([0,0,4,10,5])
    y = np.array([0,1,1])
    print(uneven_add(x,y))

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

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