简体   繁体   English

在 pandas 中滚动一阶导数和二阶导数

[英]Rolling first derivative and second derivative in pandas

I'm trying to create a function to find the rolling derivatives (first and second) in Pandas.我正在尝试创建 function 以在 Pandas 中找到滚动导数(第一和第二)。 I find that df.diff() is quite convenient.我发现df.diff()非常方便。

I want to find the derivatives with the rolling window value = 40.我想找到滚动 window 值 = 40 的导数。

For the first derivative,对于一阶导数,

noise = np.random.normal(size=int(1e4))
noise=pd.DataFrame(noise)
first_derivative=noise.diff(periods=40)

Is it correct if I use this for the second derivative?如果我将它用于二阶导数是否正确?

second_derivative=noise.diff(periods=40).diff()

I'm confused, but if I put periods=40 again in the second .diff() then it would be 40*40 rolling window (for the second derivative).我很困惑,但是如果我在第二个.diff()中再次输入periods=40 ,那么它将是 40*40 滚动 window (对于二阶导数)。 Thank you!谢谢!

Pandas is not a mathematical library, and its diff() operation just take discrete differences among elements, not derivatives. Pandas 不是数学库,它的diff()操作只是取元素之间的离散差异,而不是导数。

In order to take derivatives, I would recommend you to use SymPy , a nice Python library for symbolic mathematics.为了获取导数,我建议您使用SymPy ,这是一个用于符号数学的不错的 Python 库。 Check documentation for further details.检查文档以获取更多详细信息。

Example:例子:

from sympy import *

>> diff(cos(x), x)
-sin(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM