python - 如何使用 binned_statistic 计算非零值
问题描述
我需要有效地处理非常大的一维数组,每个 bin 提取一些统计信息,我发现 scipy.stats 中的函数 binned_statistic 非常有用,因为它包含一个非常有效的“统计”参数。
我想执行“计数”功能,但不考虑零值。
我在同一个数组上与滑动窗口(熊猫滚动函数)并行工作,它可以很好地将零替换为 NaN,但这种行为并不适用于我的案例。
这是我正在做的一个玩具示例:
import numpy as np
import pandas as pd
from scipy.stats import binned_statistic
# As example with sliding windows, this returns just the length of each window:
a = np.array([1., 0., 0., 1.])
pd.Series(a).rolling(2).count() # Returns [1.,2.,2.,2.]
# You can make the count to do it only if not zero:
nonzero_a = a.copy()
nonzero_a[nonzero_a==0.0]='nan'
pd.Series(nonzero_a).rolling(2).count() # Returns [1.,1.,0.,1.]
# However, with binned_statistic I am not able to do anything similar:
binned_statistic(range(4), a, bins=2, statistic='count')[0]
binned_statistic(range(4), nonzero_a, bins=2, statistic='count')[0]
binned_statistic(range(4), np.array([1., False, None, 1.], bins=2, statistic='count')[0]
所有之前的运行都提供相同的输出:[2., 2.] 但我期待 [1., 1.]。
找到的唯一选择是传递一个自定义函数,但它的性能比实际案例中实现的函数差得多。
binned_statistic(range(4), a, bins=2, statistic=np.count_nonzero)
解决方案
我找到了一种简单的方法来复制将数组转换为 0-1 并应用总和的非零计数:
# Transform all non-zero to 1s
a = np.array([1., 0., 0., 2.])
nonzero_a = a.copy()
nonzero_a[nonzero_a>0.0]=1.0 # nonzero_a = [1., 0., 0., 1.]
binned_statistic(np.arange(len(nonzero_a)), nonzero_a, bins=bins, statistic='sum')[0] # Returns [1.0, 1.0]
推荐阅读
- java - 按下按钮后如何延迟一行代码
- python - Python请求从streaminghttpresponse获取内容
- reactjs - Material UI:在父元素悬停时显示子元素
- sql-server - 如何在 SQL Server 容器中更改数据库备份的文件所有权
- node.js - Heroku 部署:找不到模块:'react-bootstrap'。确保已安装此软件包
- java - 创建名称为“requestMappingHandlerAdapter”Spring Boot 的 bean 时出错
- python - 超集烧瓶工厂创建管理员不工作
- ios - installProfile 命令 - 无法解析配置文件数据(签名配置文件)
- python - 使用线程的动画
- node.js - gitlab ci 为什么在获取更改时删除 node_modules 以及我们如何跳过删除