>> np.random.seed([3,1415]) >>> a = np.random.choice([True, False], (4, 8)) >>> a -6ren">
gpt4 book ai didi

python - 如何累计 "all"

转载 作者:太空狗 更新时间:2023-10-29 18:26:09 27 4
gpt4 key购买 nike

设置
考虑 numpy 数组 a

>>> np.random.seed([3,1415])
>>> a = np.random.choice([True, False], (4, 8))

>>> a
array([[ True, False, True, False, True, True, False, True],
[False, False, False, False, True, False, False, True],
[False, True, True, True, True, True, True, True],
[ True, True, True, False, True, False, False, False]], dtype=bool)

问题
对于每一列,我想确定所有的累积当量。

结果应该是这样的:

array([[ True, False,  True, False,  True,  True, False,  True],
[False, False, False, False, True, False, False, True],
[False, False, False, False, True, False, False, True],
[False, False, False, False, True, False, False, False]], dtype=bool)

取第一列

a[: 0]

# Original First Column
array([ True, False, False, True], dtype=bool)
# So far so good
# \ False from here on
# | /---------------\
array([ True, False, False, False], dtype=bool)
# Cumulative all

所以基本上,只要我们有 True 并且从那时起在第一个 False 变成 False ,累积所有都是 True


我尝试过的
我可以得到结果

a.cumprod(0).astype(bool)

但是,当我知道从我看到的第一个 False 开始一切都将是 False 时,我不禁想知道是否有必要执行每一个乘法。

考虑更大的一维数组

b = np.array(list('111111111110010101010101010101010101010011001010101010101')).astype(int).astype(bool)

我认为这两个产生相同的答案

bool(b.prod())

b.all()

但是b.all()可以短路,而b.prod()不会。如果我给他们计时:

%timeit bool(b.prod())
%timeit b.all()

100000 loops, best of 3: 2.05 µs per loop
1000000 loops, best of 3: 1.45 µs per loop

b.all() 更快。这意味着我必须有一种方法可以比我的 a.cumprod(0).astype(bool)

更快地进行累积

最佳答案

All ufuncs have 5 methods :reduceaccumulatereduceatouterat。在这种情况下,使用 accumulate 因为它返回 ufunc 的累积应用的结果:

In [41]: np.logical_and.accumulate(a, axis=0)
Out[50]:
array([[ True, False, True, False, True, True, False, True],
[False, False, False, False, True, False, False, True],
[False, False, False, False, True, False, False, True],
[False, False, False, False, True, False, False, False]], dtype=bool)

In [60]: np.random.seed([3,1415])

In [61]: a = np.random.choice([True, False], (400, 80))

In [57]: %timeit np.logical_and.accumulate(a, axis=0)
10000 loops, best of 3: 85.6 µs per loop

In [59]: %timeit a.cumprod(0).astype(bool)
10000 loops, best of 3: 138 µs per loop

关于python - 如何累计 "all",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44555293/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com