Determining the Matches of Python Two-Dimensional and One-Dimensional Arrays

Asked 2 years ago, Updated 2 years ago, 21 views

I'm a beginner, so please teach me.

I would like to determine if the values of 2D array a and 1D array b match.

a=np.array([1,1], [2,4], [2,6], [3,6], [4,6], [2,8], [4,8], [6,8], [3,9]]
b = np.array ([1,1])
if(b!=a).all():
    print("OK")
else:
    print('NG')

As a result

NG

appears.

python

2022-09-30 18:34

2 Answers

import numpy as np
a=np.array([1,1], [2,4], [2,6], [3,6], [4,6], [2,8], [4,8], [6,8], [3,9])
b = np.array ([1,1])
c=np.array ([9,9])
(a==b).all(axis=1).any()#=>True
(a==c).all(axis=1).any()#=>False

I think I have a hobby, but I think this is the best way to write.
Let's start with the code description.

(a==b)  

This checks to see if each element is equal.
Since a and b do not have the same shape, this calculation uses a function called broadcast of numpy to determine if b is equal or not equal to a, considering b to be the same shape as a.
In this comparison, we compare each element.You may know what the results will be, but if you don't know, please verify them with ipython.

.all(axis=1)

This returns True if all elements are true for Axis=1 (i.e., line direction).
Now I'm adding this expression because I want to determine if it's equivalent or not for a one-dimensional line called b.

any()

This returns True if any of the above results are true and False otherwise.
I would like to use this writing method as my answer because it accurately expresses the problem, and because it can be processed without losing performance by using the numpy function.

(b!=a).all()

The reason why this code doesn't work is that the first line of a is the same as b, so the two-dimensional array (b!=a) contains elements that are judged to be false, and if all() is called without arguments, "NG" will be printed.


2022-09-30 18:34

Is it like this?

import numpy as np
a=np.array([1,1], [2,4], [2,6], [3,6], [4,6], [2,8], [4,8], [6,8], [3,9])
b = np.array ([1,1])
"""
>>>np.all(a==b,axis=1)
array([True, False, False, False, False, False, False, False, False, False], dtype=bool)
"""
if np.all(a==b,axis=1).sum():
    print("OK")
else:
    print ("NG")


2022-09-30 18:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.