numpy数组中没有for循环的迭代

埃尔金·卡汉吉罗夫(Elgin Cahangirov)

我需要对numpy数组进行逻辑迭代,该值取决于其他数组的元素。我在下面编写了用于澄清问题的代码。有没有解决循环问题的建议吗?

Code
a = np.array(['a', 'b', 'a', 'a', 'b', 'a'])
b = np.array([150, 154, 147, 126, 148, 125])
c = np.zeros_like(b)
c[0] = 150
for i in range(1, c.size):
    if a[i] == "b":
        c[i] = c[i-1]
    else:
        c[i] = b[i]
迪卡卡

这是一种使用和的组合的方法np.maximum.accumulatenp.where以创建要在特定时间间隔停止的步进索引,然后简单地将其索引b将为我们提供所需的输出。

因此,一个实现将是-

mask = a!="b"
idx = np.maximum.accumulate(np.where(mask,np.arange(mask.size),0))
out = b[idx]

逐步执行范例-

In [656]: # Inputs 
     ...: a = np.array(['a', 'b', 'a', 'a', 'b', 'a'])
     ...: b = np.array([150, 154, 147, 126, 148, 125])
     ...: 

In [657]: mask = a!="b"

In [658]: mask
Out[658]: array([ True, False,  True,  True, False,  True], dtype=bool)

# Crux of the implmentation happens here :
In [696]: np.where(mask,np.arange(mask.size),0)
Out[696]: array([0, 0, 2, 3, 0, 5])

In [697]: np.maximum.accumulate(np.where(mask,np.arange(mask.size),0))
Out[697]: array([0, 0, 2, 3, 3, 5])# Stepped indices "intervaled" at masked places

In [698]: idx = np.maximum.accumulate(np.where(mask,np.arange(mask.size),0))

In [699]: b[idx]
Out[699]: array([150, 150, 147, 126, 126, 125])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

numpy数组中没有for循环的字典列表

没有迭代器和/或循环的Numpy数组的组合/笛卡尔积

在循环中迭代数组时,如何知道数组中是否没有更多值

for循环在python中没有完全迭代

Cython在没有gil的numpy数组列表上进行迭代

在numpy数组中迭代

在没有for循环的情况下从二维Numpy数组中删除nan条目

数组中具有一组值的循环迭代

在没有循环的情况下转换 numpy 数组

以特定模式从numpy数组生成对,而没有循环

循环数组中的迭代器

通过循环迭代numpy数组的元素

在没有for循环的情况下获取numpy 2-d数组中PER列的随机真值的索引

在没有for循环的情况下比较Numpy中两个3D矩阵的数组

如何在没有for循环的情况下在2D numpy数组中设置多个列?

numpy:有没有一种方法可以从一个没有外部循环的映射序列中创建一个数组?

如何在没有for循环的情况下在python列表/数组上迭代执行操作?

在MATLAB中检查数组中的成员资格而没有for循环

“while”循环没有正确迭代

将循环的所有迭代推入数组

MATLAB中没有for循环的多个数组的交集

有没有办法计算python中while循环中的迭代次数?

在循环中的单独数组中迭代计算

使用JavaScript中的for循环迭代对象数组

在数组中创建循环迭代列表

无限循环迭代Python中数组的列

遍历具有numpy数组的阶数和均值,没有for循环

如何在没有 for 循环的情况下将从 C++ 获得的数组转换为 Python 中的 2D numpy 数组

Python中的Numpy数组“ for”循环