Home > OS >  Element-wise comparison of numpy array (Python)
Element-wise comparison of numpy array (Python)

Time:12-17

I'd like to ask a question for the table below. Which coding should be ok for comparing the each row with other rows in the array except itself.

For example, I want to compare first row with the rest of the columns to observe whether the values of the first row smaller than any of the rest of the column.

for example:

5>2, 8>9,9<5 it is not because 8>9 is not true);
5>4, 8>5,9>11 it is not as well
5>3,  8>7, 9>8 it should be the final answer.

a=[5,8,9]
b=[2,9,5]
c=[4,5,11]
d=[3,7,8]

Which python code should be implemented to get this particular return?

I've tried lots of code blocks but never get to answer so if anyone who knows how to get it done could help me out, I'd be appreciated.

CodePudding user response:

You could use a simple function to compare two items whether separate Lists or rows of a numpy array:

def cmp(i, j):
    for x, y in zip(i, j):
        if x < y:
            return False
    return True

so for your Lists

print(cmp(a, c))
print(cmp(a, d))

CodePudding user response:

You can do this for example (disclaimer for mathematicians: I use 'not comparable' in a very loose sense :) ):

import numpy as np
    
a=[5,8,9]
b=[2,9,5]
c=[4,5,11]
d=[3,7,8]

ax = np.array([a, b, c, d])

def compare(l1,l2):
    if all([x1>x2 for x1,x2 in zip(l1,l2)]):
        return f'{l1} > {l2}'
    elif all([x1<x2 for x1,x2 in zip(l1,l2)]):
        return f'{l1} < {l2}'
    else:
        return f'{l1} and {l2} are not comparable'
    
for i in range(len(ax)):
    print([compare(ax[i],ax[j]) for j in range(len(ax)) if j!=i])

Output:

# ['[5 8 9] and [2 9 5] are not comparable', '[5 8 9] and [ 4  5 11] are not comparable', '[5 8 9] > [3 7 8]']
# ['[2 9 5] and [5 8 9] are not comparable', '[2 9 5] and [ 4  5 11] are not comparable', '[2 9 5] and [3 7 8] are not comparable']
# ['[ 4  5 11] and [5 8 9] are not comparable', '[ 4  5 11] and [2 9 5] are not comparable', '[ 4  5 11] and [3 7 8] are not comparable']
# ['[3 7 8] < [5 8 9]', '[3 7 8] and [2 9 5] are not comparable', '[3 7 8] and [ 4  5 11] are not comparable']
  • Related