簡體   English   中英

從熊貓DataFrame或系列插值到新的DatetimeIndex

[英]Interpolating from a pandas DataFrame or Series to a new DatetimeIndex

假設我有一個按小時排列的大熊貓系列,可以很好地假設來源是正常的,但那是空洞的。 如果我想將其插值到15分鍾,pandas API提供resample(15min).interpolate('cubic') 它可以插值到新的時間,並可以控制插值的極限。 樣條曲線有助於完善系列並填補一些空白。 具體來說:

tndx = pd.date_range(start="2019-01-01",end="2019-01-10",freq="H")    
tnum = np.arange(0.,len(tndx))
signal = np.cos(tnum*2.*np.pi/24.)

signal[80:85] = np.nan   # too wide a gap
signal[160:168:2] = np.nan   # these can be interpolated

df = pd.DataFrame({"signal":signal},index=tndx)    
df1= df.resample('15min').interpolate('cubic',limit=9)

現在,假設我有一個不規則的日期時間索引。 在下面的示例中,第一個時間是一個常規時間點,第二個時間是較大的時間間隔,最后一個時間是穿插的短暫時間間隔。

tndx2 = pd.DatetimeIndex('2019-01-04 00:00','2019-01-04 10:17','2019-01-07 16:00')

如何從原始序列(每小時)到這個不規則的時間序列進行插值?

建立包含原始數據和目標數據的系列的唯一選擇是嗎? 我該怎么做? 實現插值到獨立的不規則索引並施加差距限制的目標的最經濟方法是什么?

在不規則的時間標記的情況下,第一設置日期時間作為索引,然后可以使用interpolate方法來index df1= df.resample('15min').interpolate('index')

您可以在這里找到更多信息https://pandas.pydata.org/pandas-docs/version/0.16.2/genic/pandas.DataFrame.interpolate.html

這是pandas插值API中的示例解決方案,它似乎沒有辦法使用橫坐標和源序列中的值作為獨立的數據結構插值到目標索引提供的新時間。 此方法通過將目標附加到源來解決此問題。 該方法利用了df.interpolatelimit參數,並且可以使用該API中的任何插值算法,但這並不是完美的方法,因為該限制是根據值的數量以及是否有很多目標點組成的。那些NaN補丁也會被計算在內。

tndx = pd.date_range(start="2019-01-01",end="2019-01-10",freq="H")    
tnum = np.arange(0.,len(tndx))
signal = np.cos(tnum*2.*np.pi/24.)

signal[80:85] = np.nan
signal[160:168:2] = np.nan
df = pd.DataFrame({"signal":signal},index=tndx)

# Express the destination times as a dataframe and append to the source
tndx2 = pd.DatetimeIndex(['2019-01-04 00:00','2019-01-04 10:17','2019-01-07 16:00'])
df2 = pd.DataFrame( {"signal": [np.nan,np.nan,np.nan]} , index = tndx2)
big_df = df.append(df2,sort=True)  

# At this point there are duplicates with NaN values at the bottom of the DataFrame
# representing the destination points. If these are surrounded by lots of NaNs in the source frame
# and we want the limit argument to work in the call to interpolate, the frame has to be sorted and duplicates removed.     
big_df = big_df.loc[~big_df.index.duplicated(keep='first')].sort_index(axis=0,level=0)

# Extract at destination locations
interpolated = big_df.interpolate(method='cubic',limit=3).loc[tndx2]

暫無
暫無

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

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