gpt4 book ai didi

python - 计算Series的局部时间导数

转载 作者:太空狗 更新时间:2023-10-29 21:05:06 25 4
gpt4 key购买 nike

我有从 hdf5 文件导入的数据。所以,它看起来像这样:

import pandas as pd
tmp=pd.Series([1.,3.,4.,3.,5.],['2016-06-27 23:52:00','2016-06-27 23:53:00','2016-06-27 23:54:00','2016-06-27 23:55:00','2016-06-27 23:59:00'])
tmp.index=pd.to_datetime(tmp.index)

>>>tmp
2016-06-27 23:52:00 1.0
2016-06-27 23:53:00 3.0
2016-06-27 23:54:00 4.0
2016-06-27 23:55:00 3.0
2016-06-27 23:59:00 5.0
dtype: float64

我想找到数据的局部斜率。如果我只是做 tmp.diff() 我确实得到了值(value)的局部变化。但是,我想获得每秒值的变化(时间导数)我想做这样的事情,但这是错误的做法并给出了错误:

tmp.diff()/tmp.index.diff()

我发现我可以通过将所有数据转换为 DataFrame 来做到这一点,但这似乎效率不高。特别是,因为我将不得不分 block 处理磁盘上的大型文件。除了这个还有更好的方法吗:

df=pd.DataFrame(tmp)
df['secvalue']=df.index.astype(np.int64)/1e+9
df['slope']=df['Value'].diff()/df['secvalue'].diff()

最佳答案

使用numpy.gradient

import numpy as np
import pandas as pd

slope = pd.Series(np.gradient(tmp.data), tmp.index, name='slope')

为了解决时间索引不相等的问题,我会在几分钟内重新采样并进行插值。那么我的梯度将在相等的间隔内。

tmp_ = tmp.resample('T').interpolate()

slope = pd.Series(np.gradient(tmp_.data), tmp_.index, name='slope')

df = pd.concat([tmp_.rename('data'), slope], axis=1)
df

enter image description here

df.plot()

enter image description here

关于python - 计算Series的局部时间导数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com