python
主页 > 脚本 > python >

numpy.unique()使用方法介绍

2023-02-21 | 佚名 | 点击:

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

1. 参数说明

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. 一维数组

1

2

np.unique([1, 1, 2, 2, 3, 3])

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

结果

array([1, 2, 3])

2.2. 二维数组

1

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. 返回索引

1

2

a = np.array(['a', 'b', 'b', 'c', 'a'])

u, indices = np.unique(a, return_index=True)

结果

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

2.4. 重建输入矩阵

1

2

3

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])

示例:尝试用参数 return_counts 解决一个小问题。

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

# coding: utf-8

import numpy as np

  

# 任务: 统计 a 中元素个数, 找出出现次数最多的元素

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

  

# numpy.unique() 测试

b = np.unique(a)

print(b)

  

# 使用 return_counts=True 统计元素重复次数

b, count = np.unique(a, return_counts=True)

print(b, count)

  

# 使用 zip 将元素和其对应次数打包成一个个元组, 返回元组的列表

zipped = zip(b, count)

# for i, counts in zipped:

#     print("%d: %d" % (i, counts))  # 这里打印zipped出来,

#                                    # 下面 max()会报

#                                    # ValueError: max() arg is an empty sequence

#                                    # 不知道为什么 >_<

  

# 使用 max() 函数找出出现次数最多的元素

target = max(zipped, key=lambda x: x[1])

print(target)

原文链接:https://blog.csdn.net/xhtchina/article/details/129025249
相关文章
最新更新