- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
>> np.random.seed([3,1415]) >>> a = np.random.choice([True, False], (4, 8)) >>> a -6ren">
设置
考虑 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 :reduce
、accumulate
、reduceat
、outer
和 at
。在这种情况下,使用 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/
我对以下需要使用 SQL 查询而不是 plsql 来解决的问题感到困惑。这个想法是建立一个累积列来计算之前的所有月份。输入表看起来像 Month 1 2 3 .. 24 我需要建立下表:
我正在寻找一个整洁的解决方案,最好使用 tidyverse 这个问题符合this answer ,但它确实有一个额外的扭曲。我的数据有一个整体分组变量“grp”。在每个这样的组中,我想根据“试验”定义
我正在尝试在 Spotfire 中创建一个运行余额列,该列应该如下图所示。本质上,我想逐行计算“金额”列的累积总计,并且我希望它随着日期的变化从 0 开始。 我尝试过几个 OVER 函数:Sum([A
我是一名优秀的程序员,十分优秀!