numpy.unique()使用方法

numpy.unique() 函数接受一个数组,去除其中重复元素,并按元素由小到大返回一个新的无元素重复的元组或者列表。

1. 参数说明

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

ar:输入数组,除非设定了下面介绍的axis参数,否则输入数组均会被自动扁平化成一个一维数组

return_index:(可选参数,布尔类型),如果为True则结果会同时返回被提取元素在原始数组中的索引值(index)。

return_inverse:(可选参数,布尔类型),如果为True则结果会同时返回元素位于原始数组的索引值(index)。

return_counts:(可选参数,布尔类型),如果为True则结果会同时每个元素在原始数组中出现的次数。

axis:计算唯一性时的轴

返回值:返回一个排好序列的独一无二的数组。

2. 示例

2.1. 一维数组

np.unique([1, 1, 2, 2, 3, 3])
a = np.array([[1, 1], [2, 3]])

结果

array([1, 2, 3])

2.2. 二维数组

a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
np.unique(a, axis=0)

结果

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

2.3. 返回索引

a = np.array(['a', 'b', 'b', 'c', 'a'])
u, indices = np.unique(a, return_index=True)

结果

扫描二维码关注公众号,回复: 14608316 查看本文章
array([0, 1, 3])
array(['a', 'b', 'c'], dtype='<U1')

2.4. 重建输入矩阵

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

结果

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

参考文献

numpy.unique()函数_勤奋的大熊猫的博客-CSDN博客_numpy.unique

numpy.unique — NumPy v1.24 Manual

猜你喜欢

转载自blog.csdn.net/xhtchina/article/details/129025249