np.unique:如何在NumPy数组中获取唯一值

1,927 阅读3分钟

np.unique - How to Get Unique Values in NumPy Array Python

np.unique() 是一个numpy库函数,用于返回数组中所有的唯一元素。返回的数组不包含重复的元素。np.unique() 函数可以用来删除重复的元素。它只返回一次所有的元素。unique()函数还有其他参数,比如返回索引。它返回唯一元素的索引。

语法

numpy.unique(arr, return_index=False, return_inverse=False, return_counts=False, axis=None)

参数

np.unique() 函数将一个必要参数作为参数,四个参数作为可选参数。

  1. arr:数组在这个参数中被传递。从这个数组中,该函数返回唯一的元素。这个数组是返回唯一元素的必要参数。这是因为没有数组我们不能返回唯一元素。
  2. return_index。这个参数只接受布尔值作为参数。它有两个布尔值声明。True,另一个是False。如果值为True,那么np.unique()函数返回两个值:唯一数组和该唯一元素的索引。如果是False,它只返回唯一数组。
  3. return_inverse。这个参数只接受布尔值作为参数。这有两个布尔语句。True,另一个是False。如果是True,那么这个函数返回两个值:唯一数组和唯一数组元素中的原数组元素的索引。而如果是False,它只返回数组。
  4. return_counts:这个参数只接受布尔值作为参数。这有两个布尔语句。True,另一个是False。如果是True,这个函数返回两个值:一个是唯一数组,另一个是原数组中每个唯一元素的计数。如果是假的,它只返回数组。
  5. axis(轴)。这指定了返回唯一元素的轴。默认情况下,这被设置为

返回值

它返回一个数组。 这个数组由原数组中所有的唯一元素组成。如果参数中的return_indexreturn_inversereturn_counts被传递为True,那么np.unique()函数返回一个原始数组,而参数的数组被传递为True

使用np.unique从数组中寻找唯一元素的Python程序

# Importing numpy as np
import numpy as np

# Creating an numpy array
arr = np.array([5, 6, 7, 5, 7, 8, 3, 4, 3, 3])

# Finding the unique values using the unique function
res = np.unique(arr)
print(res)

输出

[3 4 5 6 7 8]

我们在这个程序中导入了一个由数值计算的函数组成的numpy

在下一步,我们使用 np.array() 函数创建了一个numpy数组。这个创建的数组由重复的值组成。然后,我们将数组传入 np.unique() 函数。

np.unique() 函数返回数组中所有的唯一元素。它只返回数组中的所有元素一次。在这个例子中,5出现在两个地方,但是np.array() 函数只返回一次。

np.unique()函数按升序返回唯一值。我们将数组作为参数传给了该函数。

通过在np.unique()函数中传递参数从数组中寻找唯一元素的程序

# Importing numpy as np
import numpy as np

# Creating an numpy array
arr = np.array([5, 6, 7, 5, 7, 8, 3, 4, 3, 3])

# Finding the unique values using the unique function
uni, index = np.unique(arr, return_index=True)
print(" The unique array is: ", uni, " and the indices are ", index)
uni, inver = np.unique(arr, return_inverse=True)
print(" The unique array is: ", uni, " and the inverses are ", inver)
uni, index, inver, count = np.unique(arr, return_index=True, return_inverse=True, return_counts=True)
print(" The unique array is: ", uni, " and the indices are ", index, " and the inverses are ", inver, " counts are: ", count)

输出

The unique array is: [3 4 5 6 7 8] and the indices are [6 7 0 1 2 5]
The unique array is: [3 4 5 6 7 8] and the inverses are [2 3 4 2 4 5 0 1 0 0]
The unique array is: [3 4 5 6 7 8] and the indices are [6 7 0 1 2 5] and the inverses are [2 3 4 2 4 5 0 1 0 0] counts are: [3 1 2 1 2 1]

这个程序传递了return_indexreturn_inversereturn_counts的参数。return_index参数返回唯一元素的索引。

return_inverse参数中,将原数组中的元素与唯一数组的索引进行比较。例如,原数组的第一个元素是5,这个5存在于唯一元素的2个索引中,因此2被作为索引返回。

这个np.unique() 函数就到此为止。