python - python - 如何在numpy中应用熊猫滚动?
问题描述
我想将pandas.rolling(window).apply(func)
范例应用于 numpy 数组。在搜索时遇到了 numpy 的这个函数。这就是我用它做的。
def rolling_apply(fun, a, w):
r = np.empty(a.shape)
r.fill(np.nan)
for i in range(w - 1, a.shape[0]):
r[i] = fun(a[(i-w+1):i+1])
return r
def test(x):
return x.sum()
arr=np.random.rand(20)
e=rolling_apply(test,arr,10)
运行时出现此错误
ValueError:使用序列设置数组元素。
你能告诉我为什么会发生这个错误吗
编辑:
这工作我在上面的代码中犯了一个初始错误。这是有效的
解决方案
数组形状和索引有点混乱。快速解决:
def rolling_apply(fun, a, w):
r = np.empty((a.shape[0]-w+1, w))
r.fill(np.nan)
for i in range(w - 1, a.shape[0]):
r[i-w+1] = fun(a[(i-w+1):i+1])
return r
def test(x):
return x*2
arr=np.random.rand(20)
e=rolling_apply(test,arr,10)
推荐阅读
- javascript - 使用 jQuery 使用右/左箭头键导航幻灯片
- java - 我不明白为什么 mkdir() 返回 false?
- ios - UITableView 单元格自动尺寸在第一次尝试中工作但在之后不起作用
- entity-framework-core - Entity Framework Core,DB生成后运行sql的最佳方式是什么
- java - 为什么 spring-boot-data-jdbc 查询方法需要 No Args 构造函数
- jenkins - Jenkins构建运行后,有什么方法可以将文件存储或更新到One-drive?
- mysql - 如何在nodejs中读取varbinary数据类型值
- cassandra-3.0 - Cassandra 在一致性 LOCAL_ONE 读取查询期间超时(等待修复不一致副本时超时)
- node.js - 谁能告诉我为什么无论“if”条件的结果如何,这总是执行“else”部分[node js]
- php - 排序关联数组 - PHP