下面的操作我必须多次进行.使用numpy函数而不是循环,我通常会获得非常好的性能,但我无法将其复制到更高维度的数组中.欢迎任何建议或替代方案:

我有一个布尔数组,我想将真索引传播到接下来的2个位置,例如:

如果该一维数组(A)是:

import numpy as np

# Number of positions to propagate the array
propagation = 2

# Original array
A = np.array([False, True, False, False, False, True, False, False, False, False, False, True, False])

我可以创建一个"空"数组,然后找到索引、传播它们,然后拉平 在哪里,然后压平它:

B = np.zeros(A.shape, dtype=bool)

# Compute the indeces of the True values and make the two next to it True as well
idcs_true = np.argwhere(A) + np.arange(propagation + 1)
idcs_true = idcs_true.flatten()
idcs_true = idcs_true[idcs_true < A.size] # in case the error propagation gives a great
B[idcs_true] = True

# Array
print(f'Original array     A = {A}')
print(f'New array (2 true) B = {B}')

其中给出:

Original array     A = [False  True False False False  True False False False False False  True
 False]
New array (2 true) B = [False  True  True  True False  True  True  True False False False  True
  True]

然而,这会变得更加复杂并且失败,例如:

AA = np.array([[False, True, False, False, False, True, False, False, False, False, False, True, False],
               [False, True, False, False, False, True, False, False, False, False, False, True, False]])

感谢任何建议.

推荐答案

I just leave here version so you can compare the speed against the proposed solution:

import numba
import numpy as np


@numba.njit(parallel=True)
def propagate_true_numba(arr, n=2):
    out = np.zeros_like(arr, dtype="uint8")

    for i in numba.prange(arr.shape[0]):
        prop = 0
        for j in range(arr.shape[1]):
            if arr[i, j] == 1:
                prop = n
                out[i, j] = 1
            elif prop:
                prop -= 1
                out[i, j] = 1

    return out

基准 :

import numba
import numpy as np
import perfplot


@numba.njit(parallel=True)
def propagate_true_numba(arr, n=2):
    out = np.zeros_like(arr, dtype="uint8")

    for i in numba.prange(arr.shape[0]):
        prop = 0
        for j in range(arr.shape[1]):
            if arr[i, j] == 1:
                prop = n
                out[i, j] = 1
            elif prop:
                prop -= 1
                out[i, j] = 1

    return out


def _prop_func(A, propagation):
    B = np.zeros(A.shape, dtype=bool)

    # Compute the indices of the True values and make the two next to it True as well
    idcs_true = np.argwhere(A) + np.arange(propagation + 1)
    idcs_true = idcs_true.flatten()
    idcs_true = idcs_true[
        idcs_true < A.size
    ]  # in case the error propagation gives a great
    B[idcs_true] = True
    return B


def propagate_true_numpy(arr, n=2):
    return np.apply_along_axis(_prop_func, 1, arr, n)


AA = np.array([[False, True, False, False, False, True, False, False, False, False, False, True, False],
             [False, True, False, False, False, True, False, False, False, False, False, True, False]])

x = propagate_true_numba(AA, 2)
y = propagate_true_numpy(AA, 2)
assert np.allclose(x, y)

np.random.seed(0)

perfplot.show(
    setup=lambda n: np.random.randint(0, 2, size=(n, n), dtype="uint8"),
    kernels=[
        lambda arr: propagate_true_numpy(arr, 2),
        lambda arr: propagate_true_numba(arr, 2),
    ],
    labels=["numpy", "numba"],
    n_range=[10, 25, 50, 100, 250, 500, 1000, 2500, 5000],
    xlabel="N * N",
    logx=True,
    logy=True,
    equality_check=np.allclose,
)

在我的AMD 5700 x上创建此图表:

enter image description here

Python相关问答推荐

我必须将Sigmoid函数与r2值的两种类型的数据集(每种6个数据集)进行匹配,然后绘制匹配函数的求导.我会犯错

使用Keras的线性回归参数估计

将DF中的名称与另一DF拆分并匹配并返回匹配的公司

处理带有间隙(空)的duckDB上的重复副本并有效填充它们

' osmnx.shortest_track '返回有效源 node 和目标 node 的'无'

pyscript中的压痕问题

部分视图的DataFrame

如何在turtle中不使用write()来绘制填充字母(例如OEG)

Python脚本使用蓝牙运行在Windows 11与raspberry pi4

python中的解释会在后台调用函数吗?

交替字符串位置的正则表达式

使用Python异步地持久跟踪用户输入

如果有2个或3个,则从pandas列中删除空格

如何在FastAPI中替换Pydantic的constr,以便在BaseModel之外使用?'

Scipy差分进化:如何传递矩阵作为参数进行优化?

Python:从目录内的文件导入目录

如何写一个polars birame到DuckDB

将相应的值从第2列合并到第1列(Pandas )

如何将列表从a迭代到z-以抓取数据并将其转换为DataFrame?

通过对列的其余部分进行采样,在Polars DataFrame中填充_null`?