如何比较两个numpy数组中的元素并添加其他元素?

时间:2019-04-22 07:03:58

标签: python python-3.x numpy

我有两个长度不同(约25k)的numpy数组,看起来像:

a = [['0110000TPK019906K' '325096'] ['0110000TPK01PR12' '225091']...]

b = [['0110000TPK019906K' '4']['0110000TPK01TGTX12K' '5']...]

我需要找到所有相似的元素a [i] [0]和b [i] [0],并将b [i] [1]添加到数组a中。结果应为:

a = [['0110000TPK019906K' '325096' '4']

所以我写了这段代码,我有什么问题吗?

i = 0    
while ( ): # which condition I should use?
        if a[0][i] == b[0][i]:
                quantity = b[0][1]
                np.append(a[0], b[i][1])
        else:
            # how go to next element in array b?

或者,也许存在更有效的方法?

1 个答案:

答案 0 :(得分:1)

您可以使用list-comprehension

new_array = np.array([[i[0],i[1],j[1]] for i,j in zip(a,b) if i[0]==j[0]])

print(new_array)

输出:

[['0110000TPK019906K' '325096' '4']]