Numpy中的多数组操作 [英] Multiple array manipulation in Numpy

查看:68
本文介绍了Numpy中的多数组操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A = [[4,0,1],
[8,0,1]]

A= [[4,0,1], [8,0,1]]

B = [[4,1,1 ],
[8,0,1]]

B = [[4,1,1], [8,0,1]]

输出= [[4,0,1],
[8,0,1 ]]

Output= [[4,0,1], [8,0,1]]

我有2个numpy数组A和B,我想得到一个输出nparray,它类似于2个原始数组中值的异或,即如果单元格相同,请保留该值;如果它们不同,请在此处放置一个0。做这个的最好方式是什么?
提前谢谢。

I have 2 numpy arrays A and B and I want to get an output nparray which is like an XOR of the values in the 2 original array i.e. if the cells are same, keep the value, if they are different, put a 0 there. What is the best way to do this? Thank You in advance.

推荐答案

虽然其中是一个不错的选择,但您应该学习

While where is a nice one-liner, you should learn how to do this with simple boolean masking.

In [9]: A= np.array([[4,0,1], [8,0,1]])
In [10]: B =np.array( [[4,1,1], [8,0,1]])

一个布尔数组,显示元素不匹配的地方

A boolean array showing where the elements don't match

In [11]: A!=B
Out[11]: 
array([[False,  True, False],
       [False, False, False]], dtype=bool)

使用它来修改 A :

In [12]: C=A.copy()
In [13]: C[A!=B]=0
In [14]: C
Out[14]: 
array([[4, 0, 1],
       [8, 0, 1]])

为清楚起见,我们插入一个不同的值- 1:

For clarity, let's insert a different value, -1:

In [15]: C[A!=B]=-1
In [16]: C
Out[16]: 
array([[ 4, -1,  1],
       [ 8,  0,  1]])

这篇关于Numpy中的多数组操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆