因为对于我的程序来说,快速索引Numpy数组是非常必要的,并且花哨的索引在考虑性能方面没有良好的声誉,我决定进行一些测试.特别是因为Numba发展很快,我尝试了哪种方法与numba配合得很好.
作为输入,我一直在使用以下数组进行小型数组测试:
import numpy as np
import numba as nb
x = np.arange(0, 100, dtype=np.float64) # array to be indexed
idx = np.array((0, 4, 55, -1), dtype=np.int32) # fancy indexing array
bool_mask = np.zeros(x.shape, dtype=np.bool) # boolean indexing mask
bool_mask[idx] = True # set same elements as in idx True
y = np.zeros(idx.shape, dtype=np.float64) # output array
y_bool = np.zeros(bool_mask[bool_mask == True].shape, dtype=np.float64) #bool output array (only for convenience)
Run Code Online (Sandbox Code Playgroud)
以下数组用于我的大型数组测试(y_bool此处需要处理重复数字randint):
x = …Run Code Online (Sandbox Code Playgroud) 假设我有一个长度为 N 的数据 numpy 数组和一个长度为 N 的位掩码数组。
data = [1,2,3,4,5,6,7,8,9,0]
mask = [0,1,0,1,0,1,0,1,0,1]
Run Code Online (Sandbox Code Playgroud)
是否有一种无循环的 numpy 方法来创建基于数据的新数组,这样当且仅当 mask[i] != 0 时它才获取所有数据条目?就像这样:
func(data, mask) = [2,4,6,8,0]
Run Code Online (Sandbox Code Playgroud)
或者等效地用循环表示法:
ans = []
for idx in range(mask):
if mask[idx]:
ans.append(data[idx])
ans = numpy.array(ans)
Run Code Online (Sandbox Code Playgroud)
谢谢!
我有两个numpy数组.
x = [[1,2], [3,4], [5,6]]
y = [True, False, True]
Run Code Online (Sandbox Code Playgroud)
我想获得的元素X,其对应的元素的y是True:
filtered_x = filter(x,y)
print(filtered_x) # [[1,2], [5,6]] should be shown.
Run Code Online (Sandbox Code Playgroud)
我试过了np.extract,但它似乎只在x1d数组时工作.如何提取x相应值的元素y是True?