SoFunction
Updated on 2025-03-02

How to use

The () function accepts an array, removes the duplicate elements, and returns a new tuple or list without elements from small to large to no duplicates.

1. Parameter description

(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, *, equal_nan=True)

ar: Enter the array. Unless the axis parameter introduced below is set, the input array will be automatically flattened into a one-dimensional array.

return_index: (optional parameter, boolean type), if True, the result will also return the index value (index) of the extracted element in the original array.

return_inverse: (optional parameter, boolean type), if True, the result will also return the index value (index) of the element in the original array.

return_counts: (optional parameter, boolean type), if True, the result will appear in the original array at the same time.

axis: The axis when calculating uniqueness

Return value: Returns a unique array of sequences.

2. Example

2.1. One-dimensional array

([1, 1, 2, 2, 3, 3])
a = ([[1, 1], [2, 3]])

result

array([1, 2, 3])

2.2. Two-dimensional array

a = ([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
(a, axis=0)

result

array([[1, 0, 0], [2, 3, 4]])

2.3. Return to the index

a = (['a', 'b', 'b', 'c', 'a'])
u, indices = (a, return_index=True)

result

array([0, 1, 3])
array(['a', 'b', 'c'], dtype='<U1')

2.4. Reconstruct the input matrix

a = ([1, 2, 6, 4, 2, 3, 2])
u, indices = (a, return_inverse=True)
u[indices]

result

array([1, 2, 3, 4, 6])
array([0, 1, 4, 3, 1, 2, 1])
array([1, 2, 6, 4, 2, 3, 2])

Example: Try to solve a small problem with the parameter return_counts.

# coding: utf-8
import numpy as np
 
# Task: count the number of elements in a and find the element with the most occurrencesa = ([1, 1, 1, 3, 3, 2, 2, 2, 2, 4, 5, 5])
 
# () testb = (a)
print(b)
 
# Use return_counts=True to count the number of elementsb, count = (a, return_counts=True)
print(b, count)
 
# Use zip to package elements and their corresponding times into tuples, and return to the list of tupleszipped = zip(b, count)
# for i, counts in zipped:
# print("%d: %d" % (i, counts)) # print it here,# # The following max() will report#                                    # ValueError: max() arg is an empty sequence
# # Don't know why >_< 
# Use the max() function to find the most occurrences of elementstarget = max(zipped, key=lambda x: x[1])
print(target)

References

()function

— NumPy v1.24 Manual

This is all about this article about the usage of () in this article. For more related () content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!