简体   繁体   English

使用numpy数组的元素逻辑检查

[英]Elementwise logical checks using numpy arrays

I have an array with dimensions (10x10) and i want to create another one (10x10). 我有一个尺寸为(10x10)的数组,我想创建另一个(10x10)。 Lets say the first one is called A and the second one B. I want B to have 0 value if the value of A is zero respectively or another value(specified by me) lets say c if the value of A is not zero. 假设第一个被称为A而第二个被称为B.如果A的值分别为零,或者另一个值(由我指定),如果A的值不为零,则我希望B具有0值。

something like that 类似的东西

B[i] = A[i] == 0 ? 0 : c

Can this be done automatically by numpy?Like this: 这可以通过numpy自动完成吗?像这样:

B = A == 0 ? 0:c

or must i traverse the arrays element by element? 或者我必须逐个遍历数组元素?

Editing for more info: 编辑以获取更多信息:

I have a numpy Array(10x10) A and one B same dimensions. 我有一个numpy阵列(10x10)A和一个B相同的尺寸。 I created another one 我创造了另一个

dif = A-B

now A has zero elements and B two, ergo dif has some zero elements 现在A有零元素和B两个,ergo dif有一些零元素

I want to create another one C numpy array where if A has element zero the value in C will be zero but if not then the value would be dif/A (the division of the elements) 我想创建另一个C numpy数组,其中如果A的元素为零,则C中的值将为零但如果不是则则值为dif / A(元素的除法)

You can use np.where : 你可以使用np.where

>>> A
array([[3, 2, 0, 3],
       [0, 3, 3, 0],
       [3, 1, 1, 0],
       [2, 1, 3, 1]])

>>> np.where(A==0, 0, 5)
array([[5, 5, 0, 5],
       [0, 5, 5, 0],
       [5, 5, 5, 0],
       [5, 5, 5, 5]])

This basically says where A==0 place 0 else place 5. The second and third arguments can be multidimensional arrays as long as they match the same dimension as your mask. 这基本上说是A==0地方0其他地方5.第二和第三个参数可以是多维数组,只要它们与你的掩码匹配相同的维度。

C
array([[7, 8, 8, 6],
       [5, 7, 5, 5],
       [6, 9, 9, 9],
       [9, 7, 5, 8]])

np.where(A==0 ,0, C)
array([[7, 8, 0, 6],
       [0, 7, 5, 0],
       [6, 9, 9, 0],
       [9, 7, 5, 8]])

D
array([[145, 179, 123, 129],
       [173, 156, 108, 130],
       [186, 162, 157, 197],
       [178, 160, 176, 103]])

np.where(A==0, D, C)
array([[  7,   8, 123,   6],
       [173,   7,   5, 130],
       [  6,   9,   9, 197],
       [  9,   7,   5,   8]])

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

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