2017-06-29 101 views
0

我試圖用對應於行df [row,'avg']和列('impute [col]')平均值的偏移量來置換Null值。有沒有辦法做到這一點,使該方法與.map並行?或者是否有更好的方法遍歷包含空值的索引?Python Pandas插值爲空值

test = pd.DataFrame({'a':[None,2,3,1], 'b':[2,np.nan,4,2], 
        'c':[3,4,np.nan,3], 'avg':[2.5,3,3.5,2]}); 
df = df[['a', 'b', 'c', 'avg']]; 
impute = dict({'a':2, 'b':3.33, 'c':6 }) 

def smarterImpute(df, impute): 
    df2 = df 
    for col in df.columns[:-1]: 
     for row in test.index: 
      if pd.isnull(df.loc[row,col]): 
       df2.loc[row, col] = impute[col] 
            + (df.loc[:,'avg'].mean() - df.loc[row,'avg']) 

return print(df2) 

smarterImpute(test, impute) 

回答

2

注意,在「填充」表達:

impute[col] + (df.loc[:,'avg'].mean() - df.loc[row,'avg']` 

第一項僅依賴於列和第三隻在排;第二隻是一個常數。所以,只要有需要填補的值,我們可以創建一個歸集數據框查找:

impute_df = pd.DataFrame(impute, index = test.index).add(test.avg.mean() - test.avg, axis = 0) 

然後,有一個名爲.combine_first()的方法,可以讓你填寫在NAS中的一個數據幀與他人的價值觀,這正是我們需要的。我們使用這個,我們完成了:

test.combine_first(impute_df) 

隨着熊貓,你通常想避免使用循環,並尋求利用矢量化。

+0

工作!謝謝,我不知道.combine_first方法。 – MyopicVisage