簡體   English   中英

Python:如何線性插值月度數據?

[英]Python: how to linearly interpolate monthly data?

我是python的新手,尤其是數據庫,所以請原諒。

我正在嘗試使用12個月的月度觀測數據組成的數據集進行練習,數據看起來像這樣...

print(data)

2017-04-17  156
2017-05-09  216
2017-06-11  300
2017-07-29  184
2017-08-31  162
2017-09-24   91
2017-10-15  225
2017-11-03  245
2017-12-26  492
2018-01-26  485
2018-02-18  401
2018-03-09  215
2018-04-30  258

這些每月的觀察是不定期的(每個月確實有一個,但幾乎不在同一時間)。

現在,我想使用線性插值在每個月初獲取值-

我已經嘗試了很多方法...並且能夠“手動”完成操作,但是我試圖與大熊貓和numpy接觸,我知道可以用這些方法來完成,這就是我的想法遠:我制作了一個包含數據的系列,然后執行:

resampled1 = data.resample('MS')
interp1 = resampled1.interpolate()

print(interp1)

打印:

2017-04-01   NaN
2017-05-01   NaN
2017-06-01   NaN
2017-07-01   NaN
2017-08-01   NaN
2017-09-01   NaN
2017-10-01   NaN
2017-11-01   NaN
2017-12-01   NaN
2018-01-01   NaN
2018-02-01   NaN
2018-03-01   NaN
2018-04-01   NaN

現在,我知道第一個2017-4-17應該是NaN線性插值(我相信這是默認值),在前后兩點之間插值...這是不可能的,因為我沒有4月1日之前的datapoint。 至於其他...我不確定我做錯了什么...可能只是因為我正在努力將我的頭完全圍繞在重新采樣的作用上?

您可能想要resample('D')進行插值,例如:

In []:
data.resample('D').interpolate().asfreq('MS')

Out[]:
2017-05-01  194.181818
2017-06-01  274.545455
2017-07-01  251.666667
2017-08-01  182.000000
2017-09-01  159.041667
2017-10-01  135.666667
2017-11-01  242.894737
2017-12-01  375.490566
2018-01-01  490.645161
2018-02-01  463.086957
2018-03-01  293.315789
2018-04-01  234.019231

嘗試使用RedBlackPy

from datetime import datetime
import redblackpy as rb

index = [datetime(2017,4,17), datetime(2017,5,9), datetime(2017,6, 11)]
values = [156, 216, 300]

series = rb.Series(index=index, values=values, interpolate='linear')
# Now you can access by any key with no insertion, using interpolation.
print(series[datetime(2017, 5, 1)]) # prints 194.18182373046875

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM