To find the difference between two arrays, use the numpy.setdiff1d() method. This means if we are subtracting two arrays, then setdiff1d() will subtract the common elements from the 1st array and display the rest of the elements of the 1st array.
The 1st and 2nd arrays are placed as two-parameter values as shown in the below syntax:
Syntax
1
2
3
setdiff1d(array1,array2)
Let us now see two examples and understand the concept:
Find the difference between two arrays
The numpy.setdiff1d() method is used to find the difference between two arrays in Python Numpy. Let us see an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
importnumpy asnp
# Create two arrays
n1=np.array([5,10,15,20,25,30,35,40,45,50])
n2=np.array([30,35,50,55,60,65,75,85,95,100])
print("Iterating array1...")
forainn1:
print(a)
print("\nIterating array2...")
forainn2:
print(a)
# n1 - n2
diffarr=np.setdiff1d(n1,n2)
print("\nDifference = \n",diffarr)
Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Iterating array1...
5
10
15
20
25
30
35
40
45
50
Iterating array2...
30
35
50
55
60
65
75
85
95
100
Difference=
[5101520254045]
Finding the difference between two arrays (n2 -n1)
Let us see the above example, with parameters being swapped. That means now, we will perform n2 – n1. Let us see an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
importnumpy asnp
# Create two arrays
n1=np.array([5,10,15,20,25,30,35,40,45,50])
n2=np.array([30,35,50,55,60,65,75,85,95,100])
print("Iterating array1...")
forainn1:
print(a)
print("\nIterating array2...")
forainn2:
print(a)
# Get the difference
resarr=np.setdiff1d(n2,n1)
print("\nDifference = \n",resarr)
Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Iterating array1...
5
10
15
20
25
30
35
40
45
50
Iterating array2...
30
35
50
55
60
65
75
85
95
100
Difference=
[556065758595100]
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok
No Comments