Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two numpy arrays to each other

I have two equally sized numpy arrays (they happen to be 48x365) where every element is either -1, 0, or 1. I want to compare the two and see how many times they are both the same and how many times they are different while discounting all the times where at least one of the arrays has a zero as no data. For instance:

for x in range(48):
    for y in range(365):
        if array1[x][y] != 0:
            if array2[x][y] != 0:
                if array1[x][y] == array2[x][y]:
                    score = score + 1
                else:
                    score = score - 1
return score

This takes a very long time. I was thinking to take advantage of the fact that multiplying the elements together and summing all the answers may give the same outcome, and I'm looking for a special numpy function to help with that. I'm not really sure what unusual numpy function are out there.

like image 332
Double AA Avatar asked Jul 14 '11 18:07

Double AA


People also ask

How do I compare two array lists in Python?

sort() and == operator. The list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.

How do I check if two arrays are similar in Python?

Check if two arrays are equal or not using SortingSort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.

How do I compare two arrays of different sizes Python?

pad the smaller array to be as long as the longer array, then substract one from the other and look with np. where((Arr1-Arr2)==0).

How can you tell if two arrays are identical?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

Simpy do not iterate. Iterating over a numpy array defeats the purpose of using the tool.

ans = np.logical_and(
    np.logical_and(array1 != 0, array2 != 0),
    array1 == array2 )

should give the correct solution.

like image 105
Paul Avatar answered Oct 26 '22 20:10

Paul