If I have an array

>>> a=np.array([[1,2,1],[3,4,2],[6,5,3],[7,8,4]])
>>> a
array([[1, 2, 1],
       [3, 4, 2],
       [6, 5, 3],
       [7, 8, 4]])

and I want to find if first column which have value=6 and if second column have value=5 using "IF" "ELSE"

I try with:

b=6
c=5
if (b in a[:,0]) and (c in a[:,1]):
    print ('yes')
else:
    print ('no')

the result is 'yes', but when I change b=7 and c=5, it still say 'yes'.. What's is missing from my code?

Well, as 7 is in the first column and 5 is in the second column, the result is hardly suprising

>>> a[:,0]
array([1, 3, 6, 7])
>>> a[:,1]
array([2, 4, 5, 8])
>>> 7 in a[:,0] and 5 in a[:,1]
True

EDIT: this seems to be working, extracting an array of row indices

>>> np.where((a[:,0] == 6) & (a[:,1] == 5))
(array([2]),)

Edited 1 Year Ago by Gribouillis

Is there not possible using IF ELSE, because I need to know if the conditional is achieve so I can append new data, if ELSE so I can calculate some distance between new data and old data..

Edited 1 Year Ago by ShilohAmi

You can write

if np.where((a[:,0] == 6) & (a[:,1] == 5))[0]:
    print('yes')
else:
    print('no')

Can you explain what you want to do in a more precise way ?

Your code works like a charm.. thank you so much.. that's what I need..
I want to find where value=6 in column-1, the result is row 2..
After find the result, search value in row-2 column-2/column index-1 if the value=5..
Can I ask one more time? Your code before:

>>> np.where((a[:,0] == 6) & (a[:,1] == 5))
(array([2]),)

can I get the result=2 into variable X?

The result (array([2]),) is a tuple containing a single item which is an np array. The item 0 of this tuple is the first item, ie the array. This array's item 0 is its first element, the integer 2.

Also this is interesting:

>>> import numpy as np
>>> a=np.array([[1,2,1],[3,4,2],[6,5,3],[7,8,4]])
>>> (a[:,0] == 6)
array([False, False,  True, False], dtype=bool)
>>> (a[:,1] == 5)
array([False, False,  True, False], dtype=bool)
>>> ((a[:,0] == 6) & (a[:,1] == 5))
array([False, False,  True, False], dtype=bool)
>>> ((a[:,0] == 6) & (a[:,1] == 5)).nonzero()
(array([2]),)

try >>> help(np.nonzero) for more documentation.

Edited 1 Year Ago by Gribouillis

Another possibility (finds all occurrences of search) ...

import numpy as np

a = np.array([[1,2,1],[3,4,2],[6,5,3],[7,8,4]])
print(a)

'''
[[1 2 1]
 [3 4 2]
 [6 5 3]
 [7 8 4]]
'''

search = 2
for col, column in enumerate(np.transpose(a)):
    print(col, column)
    row = 0
    for item in column:
        if item == search:
            print("{} is in column {}, row {}".format(search, col, row))
        row += 1

thank you for helping me vegaseat

Edited 1 Year Ago by ShilohAmi

This question has already been answered. Start a new discussion instead.