Saturday , December 21 2024
NumPy Set Operations

NumPy Set Operations

11 – Set Operations

Numpy Set Operations

In [1]:
import numpy as np

select the unique elements from an array

In [2]:
arr = np.array([1,1,2,2,3,3,4,5,6])
print(np.unique(arr))
[1 2 3 4 5 6]
In [3]:
# return the number of times each unique item appears
arr = np.array([1,1,2,2,3,3,4,5,6])
uniques, counts = np.unique(arr, return_counts=True)
print(uniques)
print(counts)
[1 2 3 4 5 6]
[2 2 2 1 1 1]

compute the intersection & union of two arrays

In [4]:
arr1 = np.array([1,2,3,4,5])
arr2 = np.array([3,4,5,6,7])
In [5]:
# intersection
print(np.intersect1d(arr1, arr2))
[3 4 5]
In [6]:
# union
print(np.union1d(arr1, arr2))
[1 2 3 4 5 6 7]

compute whether each element of an array is contained in another

In [7]:
print(np.in1d(arr1, arr2))
[False False  True  True  True]
In [8]:
# preserve the shape of the array in the output, if the array is of higher dimensions
print(np.isin(arr1, arr2))
[False False  True  True  True]

compute the elements in an array that are not in another

In [9]:
print(np.setdiff1d(arr1, arr2))
[1 2]

compute the elements in either of two arrays, but not both

In [10]:
print(np.setxor1d(arr1, arr2))
[1 2 6 7]

About Machine Learning

Check Also

Groupby in Pandas - Data Science Tutorials

Groupby in Pandas – Data Science Tutorials

14- Groupby Groupby in Pandas¶Pandas groupby is used for grouping the data according to the …

Leave a Reply

Your email address will not be published. Required fields are marked *