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)
工作!謝謝,我不知道.combine_first方法。 – MyopicVisage