我正在编写一个代码,它将向返回多列的函数应用滚动窗口。
输入:Pandas系列
预期的输出:3列 Dataframe
def fun1(series, ):
# Some calculations producing numbers a, b and c
return {"a": a, "b": b, "c": c}
res.rolling('21 D').apply(fun1)
字符串
res内容:
time
2019-09-26 16:00:00 0.674969
2019-09-26 16:15:00 0.249569
2019-09-26 16:30:00 -0.529949
2019-09-26 16:45:00 -0.247077
2019-09-26 17:00:00 0.390827
...
2019-10-17 22:45:00 0.232998
2019-10-17 23:00:00 0.590827
2019-10-17 23:15:00 0.768991
2019-10-17 23:30:00 0.142661
2019-10-17 23:45:00 -0.555284
Length: 1830, dtype: float64
型
错误代码:
TypeError: must be real number, not dict
型
我尝试过的:
- 更改原始值= Apply中的True
- 在apply中使用lambda函数
- 返回fun 1中的结果作为lists/numpy arrays/dataframe/series。
我也读过许多关于SO的文章,说几句:
- Pandas - Using
.rolling()
on multiple columns - Returning two values from pandas.rolling_apply的
- How to apply a function to two columns of Pandas dataframe的
- Apply pandas function to column to create multiple new columns?的
但是没有一个解决方案可以解决这个问题。
有没有直接的解决办法?
3条答案
按热度按时间vsnjm48y1#
下面是一个hacky的答案,使用
rolling
生成一个DataFrame:字符串
似乎
rolling
apply
函数总是期望返回一个数字,以便根据计算立即生成一个新的Series。我通过创建一个新的
output
DataFrame(带有所需的输出列)并在函数中写入该数据来解决这个问题。我不确定是否有一种方法可以在滚动对象中获取索引,所以我使用global
来增加写入新行的计数。根据上面的观点,你需要return
一些数字。因此,虽然实际上rolling
操作返回一系列1
,但output
被修改:型
这感觉更像是对
rolling
的利用,而不是预期的用途,所以我很有兴趣看到一个更优雅的答案。UPDATE:感谢@JuanPi,您可以使用this answer获取滚动窗口索引。因此,非
global
的答案可能如下所示:型
s4n0splo2#
这个黑客似乎对我有效,尽管滚动的附加特性不能应用到这个解决方案中。然而,由于多处理,应用程序的速度明显更快。
字符串
将上述函数设置好后,插入函数以滚动到自定义
rolling_function
中。型
结果内容:
型
注意事项:
window_size
只考虑最大窗口大小,因此所有低于window_size
的起始索引将使其窗口包括直到起始元素的所有元素。pool.map
不能接受本地函数或lambda函数,因为它们不能根据multiprocessing
库进行“pickle”pcww981p3#
你可以分别使用rolling()和apply()**来获得多个列。从原始Dataframe创建一个Rolling Dataframe一次,然后多次使用.apply()。
对于名为“df”的数据框:
字符串