Akshay
Akshay

Reputation: 2763

Row-wise comparison in numpy

Say we have two numpy arrays:

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), i.e.

[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:

[-2, 20, -4], [4, 5, 6] = [-1 1 -1]

if nothing else satisfies put 0

And for the second sample from arr, it should compare with the second 1D of comp, i.e:

[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).

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)))

Upvotes: 3

Views: 2970

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375425

The usual way to do the comparison (to -1, 0, 1) is using 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... e.g. using np.repeat/tile to give comp the same size as arr (or a something clever)!

Update: Thanks to @flippo for a pure numpy solution:

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]]])

Upvotes: 2

Related Questions