如何进行累积的“全部"操作? [英] How to do a cumulative "all"
问题描述
设置
考虑numpy数组a
Setup
Consider the numpy array 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)
问题
对于每一列,我都想确定所有列的累积等值.
Question
For each column, I want to determine the cumulative equivalent for all.
结果应如下所示:
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
So basically, cumulative all is True
as long as we have True
and turns False
from then on at the first False
我尝试过的事情
我可以用
What I have tried
I can get the result with
a.cumprod(0).astype(bool)
但是,当我知道从我看到的第一个False
开始都是False
时,我不禁想知道是否需要执行每个乘法.
But, I can't help but wonder if its necessary to perform each and every multiplication when I know everything will be False
from the first False
I see.
考虑更大的一维数组
b = np.array(list('111111111110010101010101010101010101010011001010101010101')).astype(int).astype(bool)
我认为这两个问题会产生相同的答案
I contend that these two produce the same answer
bool(b.prod())
和
b.all()
但是b.all()
可能会短路,而b.prod()
不会.如果我给他们计时:
But b.all()
can short circuit while b.prod()
does not. If I time them:
%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)
b.all()
is quicker. This implies that there must me a way to conduct a cumulative all that is quicker that my a.cumprod(0).astype(bool)
推荐答案
所有ufunc都有5种方法:reduce
,accumulate
,reduceat
,outer
和at
.在这种情况下,请使用accumulate
,因为它会返回ufunc的累积应用程序的结果:
All ufuncs have 5 methods: reduce
, accumulate
, reduceat
, outer
, and at
. In this case, use accumulate
since it returns the result of cumulative applications of the 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
这篇关于如何进行累积的“全部"操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!