What is bitwise_and() in NumPy?
Overview
The NumPy bitwise_and() method is used to evaluate bitwise logical AND operators between two arrays. It performs the bitwise logical AND operation of underlying binary representations.
Syntax
numpy.bitwise_and(arr1,arr2,out=None,where=True,**kwargs)
Parameters
It takes the following argument values:
arr1: This is an array-like object. It only handles integer and boolean-type arrays.arr2: This is an array-like object. It only handles integer and boolean-type arrays.out: This is the memory location in which the result will be stored. It will be of the same dimension asarr1orarr2. If it is set toNone, a new array of the same dimensions will be initialized.
where: This is an optional parameter. If its value isTrue, then the result of the function will be replaced with theufuncresult. If set to False, the original value will be returned as it is. Its default value isTrue.
**kwargs: These are additional arguments.
Return value
It returns ndarray or scalar type objects.
Code
In this code, we'll take a look at numpy.bitwise_and() with different argument values.
# importing numpy libraryimport numpy as np# performing logical AND between 12, 16print("12 AND 16:", end=" ")print(np.bitwise_and(12, 16))# logical AND between a Python list [3,13] and 12print("[3,13] AND 12:", end=" ")print(np.bitwise_and([3,13], 12))# logical AND between two lists of same sizeprint("[9,7] AND [8,35]:", end=" ")print(np.bitwise_and([9,7], [8,35]))# performing logical AND between two numpy arraysprint("np.array([2,7,255]) AND np.array([6,12,18]):", end=" ")print(np.bitwise_and(np.array([2,7,255]), np.array([6,12,18])))
Code explanation
- Lines 4–5: We perform bitwise AND between 12 (0000 1100) and 16 (0001 0000). This will return 0.
- Lines 7–8: We perform bitwise AND between a list [3,13]=>(0000 0011, 0000 1101) and 12 (0000 1100). This will return a list.
- Lines 10–11: We perform bitwise AND between 2 lists [9,7] and [8,35].
- Lines 13–14: We perform bitwise AND between two Numpy arrays
np.array([2,7,255])andnp.array([6,12,18].
Implementation of ufunc
Numpy also supports universal functions (ufunc) that implement C or core Python operator &.
# importing numpy libraryimport numpy as np# creating two numpy arraysx1 = np.array([4, 7, 255])x2 = np.array([8,13,19])# performing logical AND using conventional & operatorprint(x1 & x2)
Explanation
- Line 4: We create a NumPy array
x1containing [4, 7, 255].
- Line 5: We create a NumPy array
x2containing [8,13,19]. - Line 7: We perform logical AND by using a conventional
&operator.