簡體   English   中英

Python pandas dataframe:使用數據幀數據進行插值而不更新它。 只需獲取插值即可。

[英]Python pandas dataframe: interpolation using dataframe data without updating it. Just get the interpolated value.

我是Python pandas庫的新手,在其他帖子中找不到我的問題的答案。 我有一個看起來像這樣的數據框。 日期是索引名稱,系列是列名稱。

>>> MyDataframe
             Serie1  Serie2  Serie3  Serie4  Serie5 
2011-04-30      92      96     NaN     NaN     NaN  
2011-05-31     164     168      12     16      NaN
2011-06-30     238     242      90     20      88
2011-07-31     322     326     169     120     167

我想在這個數據幀中執行一維線性插值,但是沒有修改數據幀,我只想得到結果。 例如,我想確定2011-06-10日期Serie2的價值是多少。 函數DataFrame.interpolate()Series.interpolate()似乎僅用於將NaN替換為插值數據。

是否有一個可以執行以下操作的功能:

Result = MyDataFrame['Serie2'].interpolate('2011-06-10')

它只會返回168到242之間的線性插值。

在此先感謝您的支持!

使用現有索引進行interpolate插值,因此必須重新reindex df然后調用interpolate

In [48]:
df.reindex(pd.date_range(df.index[0], df.index[-1])).interpolate().loc['2011-06-10']

Out[48]:
Serie1    188.666667
Serie2    192.666667
Serie3     38.000000
Serie4     17.333333
Serie5           NaN
Name: 2011-06-10 00:00:00, dtype: float64

完成此操作后,您可以選擇特定的日期和列:

In [49]:
df.reindex(pd.date_range(df.index[0], df.index[-1])).interpolate().loc['2011-06-10']['Serie2']

Out[49]:
192.66666666666666

在這里,我使用date_range使用索引中的第一個和最后一個值生成一個新的datetimeindex

在您的范圍內的現有索引值之間進行插值會更有效。

我們可以使用get_slice_bound找到索引值的get_slice_bound

In [70]:
start = df.index.get_slice_bound('2011-06-10', side='right', kind=None)

df.reindex(pd.date_range(df.index[start-1], df.index[start])).interpolate().loc['2011-06-10']['Serie2']
Out[70]:
192.66666666666666

暫無
暫無

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

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