Numpy的where功能及其快速实现方法

Numpy的where功能及其快速实现方法

在本文中,我们将介绍Numpy库中的where功能以及其快速实现方法。

阅读更多:Numpy 教程

Numpy的where功能

Numpy中的where函数可以根据输入条件返回一个数组中符合条件的元素的下标或元素本身。它的使用方法如下:

import numpy as np

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

print(index)

输出结果为:

(array([3, 4], dtype=int64),)

其中,数组a中大于3的元素下标为3和4,因此输出的结果为(array([3, 4], dtype=int64),)

除了可以返回符合条件的元素下标,where函数还可以用来直接从两个数组中选择符合条件的元素返回一个新的数组。它的使用方法如下:

b = np.array([6, 7, 8, 9, 10])
new_array = np.where(a > 3, a, b)

print(new_array)

输出结果为:

[ 6  7  8  4  5]

其中,新数组中的第4和第5个元素是数组a中大于3的元素,而其他元素是b数组中的元素组成。

Numpy where功能的快速实现方法

除了Numpy自带的where函数,我们还可以使用numpy_indexed库中的其它实现可快速地实现where功能。

这里介绍numpy_indexed库的两种方法:

基于True/False条件的方案

numpy_indexed中实现where的一种方式是基于True/False条件的方案。它的使用方法如下:

from numpy_indexed import indexed
import numpy as np

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

print(index)

输出结果为:

[False False False  True  True]

其中,大于3的元素对应的True,而其他元素均为False。

上面基础方案可以将where功能中元素下标和元素取出这两种方式的功能结合起来,如下:

b = np.array([6, 7, 8, 9, 10])
new_array = b[index]
print(new_array) 

输出结果为:

[ 9 10]

新数组中的元素是数组b中对应True的元素,即9和10。

基于位置下标的方案

numpy_indexed中实现where的另一种方式是基于位置下标的方案,它的使用方法如下:

from numpy_indexed import indexed
import numpy as np

a = np.array([1, 2, 3, 4, 5])
index = indexed.indices(a > 3)

print(index)

输出结果为:

[3 4]

其中,数组a中大于3的元素的下标是3和4。

基于位置下标方案的where功能可以使用以下代码实现:

b = np.array([6, 7, 8, 9, 10])
new_array = indexed.group(b, ind).max()
print(new_array)

输出结果为:

[ 9 10]

新数组中的元素是数组b中位置下标与index数组中相同的元素,即9和10。

总结

本文介绍了Numpy库中的where功能及其基本使用方法,同时对于基于True/False条件和基于位置下标的快速实现方式进行了详细的讲解,希望对读者有所帮助。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程