In this article, we will see the possible causes of the error “numpy ndarray object has no attribute intersection” and how to resolve it.
The “ndarray object has no attribute intersection” error message usually occurs when we try to perform an intersection operation on a NumPy array using the intersection
method. However, unlike standard Python sets, NumPy arrays do not have an intersection method. Therefore, if we try to use the intersection method on a NumPy array, we will get a “ndarray object has no attribute intersection” error.
Let us see an example to understand more about this:
let’s create two NumPy arrays and try to find their intersection:
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
result = a.intersection(b)
When we run the above code, we will get the following error message:
When we run this code, we will get the following error message:
How to resolve?
To resolve the above error, we use the intersect1d
function provided by NumPy instead of the intersection
method. The intersect1d
function returns the sorted, unique values that are in both of the input arrays. Here is an example of how to use intersect1d
:
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
result = np.intersect1d(a, b)
print(result)
Output
[3 4]
As we can see, the intersect1d
function correctly returns the intersection of the two arrays.
Also, note that if we want to find the intersection of multiple arrays, we can simply chain the intersect1d
function
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
c = np.array([2, 3, 4])
result = np.intersect1d(a, np.intersect1d(b, c))
print(result)
Output
[3 4]