np.unique()
时间: 2023-12-03 11:02:52 浏览: 25
np.unique()是一个NumPy库中的函数,用于返回给定数组中的唯一值。它会返回一个已排序的数组,其中只包含原始数组中的唯一值。这个函数可以接受参数来指定返回的唯一值的排序方式。
例如,如果我们有一个NumPy数组arr = [1, 2, 3, 1, 2, 4],我们可以使用np.unique(arr)来获取这个数组中的唯一值。输出结果将是一个已排序的数组[1, 2, 3, 4]。
除了返回唯一值,np.unique()还可以返回唯一值的索引或计数。
希望这个回答对你有帮助!如果你还有其他问题,请随时提问。
相关问题
np.unique
`np.unique` 是 NumPy 库中的一个函数,它用于返回给定数组中的唯一元素,并按升序排列。
函数的语法如下:
```python
np.unique(arr, return_index=False, return_inverse=False, return_counts=False, axis=None)
```
参数说明:
- `arr`: 输入的数组。
- `return_index`: 如果为 True,则返回输入数组中唯一元素的索引。
- `return_inverse`: 如果为 True,则返回输入数组中唯一元素的下标。
- `return_counts`: 如果为 True,则返回输入数组中唯一元素的出现次数。
- `axis`: 用于指定沿着哪个轴计算唯一值,默认为 None。
示例:
```python
import numpy as np
arr = np.array([1, 2, 2, 3, 3, 3])
unique_arr = np.unique(arr)
print(unique_arr)
# 输出: [1 2 3]
```
np.unique 用法
`np.unique` 是 NumPy 库中的一个函数,用于查找数组中的唯一值,并将其返回为已排序的数组。
它的用法如下:
```python
np.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
```
其中,参数含义如下:
- `ar`:要查找唯一值的数组。
- `return_index`:如果为 True,则返回输入数组中唯一值的索引。
- `return_inverse`:如果为 True,则返回输入数组中唯一值的逆向索引,即将唯一值还原为原数组的索引。
- `return_counts`:如果为 True,则返回输入数组中唯一值的出现次数。
- `axis`:指定沿哪个轴查找唯一值。
举个例子:
```python
import numpy as np
arr = np.array([1, 2, 3, 2, 1, 4, 5, 4])
uniq_arr = np.unique(arr)
print(uniq_arr) # 输出 [1 2 3 4 5]
```
在这个例子中,我们使用 `np.unique` 函数查找数组 `arr` 中的唯一值,并将其存储在变量 `uniq_arr` 中。最后打印 `uniq_arr`,输出结果为 `[1 2 3 4 5]`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)