[英]Row-wise comparison in numpy
Say we have two numpy arrays: 假设我们有两个numpy数组:
arr = np.array([
[
[1, 2, 3],
[4, 5, 6],
[7, -8, 9],
[10, 11, 12]
],
[
[13, 14, -15],
[16, -17, 18],
[19, 20, 21],
[22, 23, 24]
]
])
and 和
comp = np.array([
[2, 20, 4],
[3, 8, 15]
])
I am trying to compare each 1D array of comp
to 2D array of arr
(row-wise), ie 我试图比较
comp
每个1D数组到arr
二维数组(行方式),即
[2, 20, 4] > [1, 2, 3] = [1 1 1]
if the next row doesn't satisfy the condition negate the comp
and then compare it: 如果下一行不满足条件否定
comp
然后比较它:
[-2, 20, -4], [4, 5, 6] = [-1 1 -1]
if nothing else satisfies put 0
如果没有别的东西满足于
0
And for the second sample from arr
, it should compare with the second 1D of comp
, ie: 对于来自
arr
的第二个样本,它应该与comp
的第二个1D进行comp
,即:
[2, 20, 4], [13, 14, -15] = [...]
So, it should something like, 所以,应该是这样的,
[
[
[1 1 1]
[-1 1 -1]
...
]
[
[...]
[...]
]
]
I have tried doing something like this: 我尝试过这样的事情:
for sample in arr:
for row in sample:
print(np.where(np.greater(row, comp), 1, np.where(np.less(row, -comp), -1, 0)))
But this code is comparing the complete array of comp
to arr[0][#]
and a[1][#]
(alternatively). 但是这段代码将完整的
comp
数组与arr[0][#]
和a[1][#]
(或者)进行比较。
How should I do this row wise? 我该怎么做呢?
Update: 更新:
Is this the right way of doing it?: 这是正确的做法吗?:
for idx, sample in enumerate(arr):
print(np.where(np.greater(sample, comp[idx]), 1, np.where(np.less(sample, -comp[idx]), -1, 0)))
The usual way to do the comparison (to -1, 0, 1) is using np.sign
: 进行比较(到-1,0,1)的常用方法是使用
np.sign
:
In [11]: np.sign(comp[0] - arr[0])
Out[11]:
array([[ 1, 1, 1],
[-1, 1, -1],
[-1, 1, -1],
[-1, 1, -1]])
So, this could be written as: 所以,这可以写成:
In [12]: np.array([np.sign(comp[i] - a) for i, a in enumerate(arr)])
Out[12]:
array([[[ 1, 1, 1],
[-1, 1, -1],
[-1, 1, -1],
[-1, 1, -1]],
[[-1, -1, 1],
[-1, 1, -1],
[-1, -1, -1],
[-1, -1, -1]]])
There may be a neat way to do the "subtraction" in pure numpy... eg using np.repeat/tile to give comp
the same size as arr
(or a something clever)! 在纯粹的numpy中可能有一种简洁的方法来做“减法”...例如使用np.repeat / tile来给出与
arr
相同大小的comp
(或者一些聪明的东西)!
Update: Thanks to @flippo for a pure numpy solution: 更新:感谢@flippo提供纯粹的numpy解决方案:
In [13]: np.sign(comp[:,np.newaxis,:] - arr)
Out[13]:
array([[[ 1, 1, 1],
[-1, 1, -1],
[-1, 1, -1],
[-1, 1, -1]],
[[-1, -1, 1],
[-1, 1, -1],
[-1, -1, -1],
[-1, -1, -1]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.