You could always do just:
a=[1,2,3]
b=['a','b']
c=[1,2,3,4]
d=[1,2,3]
a==b #returns False
a==c #returns False
a==d #returns True
Answer from skajfes on Stack OverflowYou could always do just:
a=[1,2,3]
b=['a','b']
c=[1,2,3,4]
d=[1,2,3]
a==b #returns False
a==c #returns False
a==d #returns True
a = ['a1','b2','c3']
b = ['a1','b2','c3']
c = ['b2','a1','c3']
# if you care about order
a == b # True
a == c # False
# if you don't care about order AND duplicates
set(a) == set(b) # True
set(a) == set(c) # True
By casting a, b and c as a set, you remove duplicates and order doesn't count. Comparing sets is also much faster and more efficient than comparing lists.
Not sure the title is a good description but essentially what I'm trying to do is:
A = [1,-1,1,1,0,0,-1]
B = [1,1,1,-1,-1,0,-1]
Output = [1,0,1,0,0,0,-1]
If element on array one is equal to element on array 2, then output the element. If not then output 0.
I'm sure there is a slick way to do this but I can't figure it out.
In the below code, in which the variable ar consist mostly of [[255. 255. 255.]...] but there are very few element that has different values. I want to extract those values and their index separately. In the below, I presented the function code and results, dtypes are same, things are done correctly but it fails. Need some help!
def get_colors(ar):
# ar shape 128 x128 x3.
shape = ar.shape
# Convert to n x 3.
ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)
print("ar : ", ar)
# identify white colors
mm = np.array([225, 225, 225]).astype(float)
print("mm : ", mm)
# to match the size of ar, we use tile
mm_broadcasted = np.tile(mm, (ar.shape[0], 1))
print("mm_broadcasted : ", mm_broadcasted)
kkk = (ar != mm_broadcasted)
print("kkk:",kkk)
not_matching = ar[(ar != mm_broadcasted).all(axis=1)]
indices = np.argwhere((ar != mm_broadcasted).all(axis=1)).ravel()
print("not_matching:", not_matching)
print("indices:", indices)
--------------------------------------------------------
Here are the result:
ar : [[255. 255. 255.]
[255. 255. 255.]
[255. 255. 255.]
...
[255. 255. 255.]
[255. 255. 255.]
[255. 255. 255.]]
mm : [225. 225. 225.]
mm_broadcasted : [[225. 225. 225.]
[225. 225. 225.]
[225. 225. 225.]
...
[225. 225. 225.]
[225. 225. 225.]
[225. 225. 225.]]
kkk: [[ True True True]
[ True True True]
[ True True True]
...
[ True True True]
[ True True True]
[ True True True]]
not_matching: [[255. 255. 255.]
[255. 255. 255.]
[255. 255. 255.]
...
[255. 255. 255.]
[255. 255. 255.]
[255. 255. 255.]]
indices: [ 0 1 2 ... 16381 16382 16383]
If you're using numpy, using numpy all the way is preferable. It will be faster, and use less memory, than the iterative approach (and is more readable, too).
np.max([array1, array2], axis=0)
Your loop is infinite because your i never changes. If you fix that (either by adding i += 1 or by using for i in range(0, len(array1)):), you will only be appending elements where array1 one is larger, and leaving out any pairs where they are equal, or where the array2 one is larger: an else: would be needed.
You're probably looking for something like numpy.maximum:
import numpy as np
array1 = np.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
array2 = np.array([11, 1, 2, 4, 10, 60, 0, 3, 20, 33])
np.maximum(array1, array2)
# array([11, 2, 3, 4, 10, 60, 7, 8, 20, 33])
(A==B).all()
test if all values of array (A==B) are True.
Note: maybe you also want to test A and B shape, such as A.shape == B.shape
Special cases and alternatives (from dbaupp's answer and yoavram's comment)
It should be noted that:
- this solution can have a strange behavior in a particular case: if either
AorBis empty and the other one contains a single element, then it returnTrue. For some reason, the comparisonA==Breturns an empty array, for which thealloperator returnsTrue. - Another risk is if
AandBdon't have the same shape and aren't broadcastable, then this approach will raise an error.
In conclusion, if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:
np.array_equal(A,B) # test if same shape, same elements values
np.array_equiv(A,B) # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values
The (A==B).all() solution is very neat, but there are some built-in functions for this task. Namely array_equal, allclose and array_equiv.
(Although, some quick testing with timeit seems to indicate that the (A==B).all() method is the fastest, which is a little peculiar, given it has to allocate a whole new array.)
There are two ways I'll show you (there are probably a lot more using NumPy):
First method: chaining operations
You can use "masking" followed by the comparison and finally a sum operation:
We want all values in a from the indices where b is equal to 1:
part1 = a[b == 1]
Now we want all places where part1 is equal to 1
part2 = part1[part1 == 1]
now we are left with all the places where a and b are equal to 1, so we can simply sum them up:
result = part2.sum()
Method 2: built in numpy.where
This is much shorted and probably faster to compute. NumPy has a nice function that returns the indices where your criteria are met in some arrays:
condition_1 = (a == 1)
condition_2 = (b == 1)
Now we can combine the operation by saying "and" - the binary operator version: &.
part1 = numpy.where(condition_1 & condition_2)
To get your desired output, we can take the length of the resulting set of indices:
result = len(part1)
Read the documentation about numpy.where to see the other things it can do for you!
I like @RobinNicole's answer - in terms of Mathematics you are looking for a product of two boolean vectors.
Here are a few Numpy ways to do that:
In [37]: np.dot(a, b)
Out[37]: 3
In [38]: a @ b
Out[38]: 3
Here is another more generic solution which will work also for not-boolean vectors:
In [48]: ((a == 1) & (b == 1)).sum()
Out[48]: 3