pandas resample interpolate is producing NaNs

后端 未结 1 1165
感动是毒
感动是毒 2021-01-12 03:48

Modified from this example:

import io
import pandas as pd
import matplotlib.pyplot as plt

data = io.StringIO(\'\'\'\\
Values
1992-08-27 07:46:48,1
1992-08-2         


        
1条回答
  •  孤城傲影
    2021-01-12 04:23

    Option 1
    That's because '4s' aligns perfectly with your existing index. When you resample, you get representation from your old series and are able to interpolate. What you want to do is to create an index that is the union of the old index with a new index. Then interpolate and reindex with a new index.

    oidx = s.index
    nidx = pd.date_range(oidx.min(), oidx.max(), freq='5s')
    res = s.reindex(oidx.union(nidx)).interpolate('index').reindex(nidx)
    res.plot(style='.-')
    s.plot(style='o')
    


    Option 2A
    If you are willing to forgo accuracy, you can ffill with a limit of 1

    res = s.resample('5s').ffill(limit=1).interpolate()
    res.plot(style='.-')
    s.plot(style='o')
    


    Option 2B
    Same thing with bfill

    res = s.resample('5s').bfill(limit=1).interpolate()
    res.plot(style='.-')
    s.plot(style='o')
    


    Option 3
    Intermediate complexity and accuracy

    nidx = pd.date_range(oidx.min(), oidx.max(), freq='5s')
    res = s.reindex(nidx, method='nearest', limit=1).interpolate()
    res.plot(style='.-')
    s.plot(style='o')
    

    0 讨论(0)
提交回复
热议问题