python - 多个切片的 NumPy 平均值
问题描述
假设我有一个数组a
,我想计算其中定义的多个切片的平均值idx
:
a = np.arange(10)
idx = np.random.choice([0,1], a.size).astype(bool)
a, idx
Out[1]: (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
array([False, False, True, True, False, False, False, True, True,
True]))
使用所需的输出:
array([2.5, 8. ])
当然,我可以编写一个简单的for
循环,但我更喜欢完全矢量化的方法,因为数组的大小可能会变得非常大并且是二维的。
解决方案
可以完全矢量化:
edges = np.diff(idx.astype(np.int8), prepend=0, append=0)
rising = np.where(edges == 1)[0]
falling = np.where(edges == -1)[0]
cum = np.insert(np.cumsum(a), 0, 0)
means = (cum[falling] - cum[rising]) / (falling - rising)
这在我的机器上大约需要 0.2 秒a = np.arange(10**7)
。
推荐阅读
- python-3.x - 逐行创建多级数据框
- django - request.POST.get('username') 返回 NONE
- java - 是否可以使用 Java 为 Java Profiler 拍摄快照?
- firebase - 如何为存在系统设置正确的 Firebase 实时安全规则
- python - 在不同系统中使用 PyUSB 从 USB 设备读取时出现问题
- ios - 即使我添加相机使用说明/照片库使用说明也不显示警报
- sonarqube - SonarJs 仍然显示有关 postMessage 跨域问题的警告
- firebase-test-lab - 测试中不能打电话
- sql-server - 一段时间后访问令牌连接失败,登录失败 NT AUTHORITY\ANONYMOUS LOGON 错误
- google-chrome - Mac VoiceOver 是否会限制其在 Chrome / Firefox 上的功能?