2015-07-10 58 views
6

當使用大熊貓插值()填寫NaN值是這樣的:熊貓插值替換NaN的,但不是第一個數據點之前

In [1]: s = pandas.Series([np.nan, np.nan, 1, np.nan, 3, np.nan, np.nan]) 

In [2]: s.interpolate() 
Out[2]: 
0 NaN 
1 NaN 
2  1 
3  2 
4  3 
5  3 
6  3 
dtype: float64 

In [3]: pandas.version.version 
Out[3]: '0.16.2' 

,爲什麼熊貓在指數5替換值和6與3s,但保留在0和1的值?

我可以改變這種行爲嗎?我想離開指數5和6的NaN。

(實際上,我希望它線性外推以填充所有0,1,5和6,但這是一個不同的問題。紅利點,如果你也回答它!)

回答

5

在內部,interpolate方法使用,其避免了填充傳播大於特定的閾值以上的「限制」參數。

>>>df=pd.DataFrame([0, np.nan, np.nan, np.nan, np.nan,np.nan, 2]) 
>>>df 
df 
    0 
0 0 
1 NaN 
2 NaN 
3 NaN 
4 NaN 
5 NaN 
6 2 
>>>df.interpolate(limit=2) 
      0 
0 0.000000 
1 0.333333 
2 0.666667 
3  NaN 
4  NaN 
5  NaN 
6 2.000000 

默認情況下,限制適用於正向。在向後的方向上,默認限制被設置爲零。這就是爲什麼你的第一步不是由方法填補。 可以使用'limit_direction'參數來改變方向。

df.interpolate(limit=2, limit_direction='backward') 
      0 
0 0.000000 
1  NaN 
2  NaN 
3  NaN 
4 1.333333 
5 1.666667 
6 2.000000 

填補了第一步,你的數據幀的最後一個步驟,可以應設置爲「限制」和「limit_direction」到「兩個」非零值:

>>> df=pd.DataFrame([ np.nan, np.nan, 0, np.nan, 2, np.nan,8,5,np.nan, np.nan]) 
>>> df 
    0 
0 NaN 
1 NaN 
2 0 
3 NaN 
4 2 
5 NaN 
6 8 
7 5 
8 NaN 
9 NaN 
>>> df.interpolate(method='spline', order=1, limit=10, limit_direction='both') 
      0 
0 -3.807382 
1 -2.083581 
2 0.000000 
3 1.364022 
4 2.000000 
5 4.811625 
6 8.000000 
7 5.000000 
8 4.937632 
9 4.138735 

的已討論的主題here

+0

你認爲在使用limit_direction ='both'(限制=無)並使用外推之間存在差異,就像在這裏爲instace所做的那樣(https://stackoverflow.com/questions/22491628/extrapolate-values-in-pandas -dataframe)? –

2

interpolate行爲在熊貓看起來很奇怪。您可以使用scipy.interpolate.interp1d來產生預期結果。對於線性外推,可以編寫一個簡單的函數來完成此任務。

import pandas as pd 
import numpy as np 
import scipy as sp 

s = pd.Series([np.nan, np.nan, 1, np.nan, 3, np.nan, np.nan]) 

# interpolate using scipy 
# =========================================== 
s_no_nan = s.dropna() 
func = sp.interpolate.interp1d(s_no_nan.index.values, s_no_nan.values, kind='linear', bounds_error=False) 
s_interpolated = pd.Series(func(s.index), index=s.index) 

Out[107]: 
0 NaN 
1 NaN 
2  1 
3  2 
4  3 
5 NaN 
6 NaN 
dtype: float64 

# extrapolate using user-defined func 
# =========================================== 
def my_extrapolate_func(scipy_interpolate_func, new_x): 
    x1, x2 = scipy_interpolate_func.x[0], scipy_interpolate_func.x[-1] 
    y1, y2 = scipy_interpolate_func.y[0], scipy_interpolate_func.y[-1] 
    slope = (y2 - y1)/(x2 - x1) 
    return y1 + slope * (new_x - x1) 

s_extrapolated = pd.Series(my_extrapolate_func(func, s.index.values), index=s.index) 

Out[108]: 
0 -1 
1 0 
2 1 
3 2 
4 3 
5 4 
6 5 
dtype: float64 
+0

謝謝。我仍然希望有人會回答熊貓發生的事情。它應該只是包裝scipy ... – foobarbecue

+0

包裝scipy將意味着熊貓有依賴於scipy,我想他們想避免。 – Jezzamon

+0

@foobarbecue你有沒有想過這個?我得到類似的問題熊貓0.18.1 – toasteez