python - how to fill NA with mean only for 2 or less consequective values of NA -
i new python. please me how should proceed. following dataframe contains large blocks of nans. # fill nas mean 2 or less consecutive values of nas. # refer documentation of fillna() find out parameter use fill certail number of nas. # resulting dataframe should df_filled
# resulting dataframe should df_filled shown below. df = pd.dataframe({'val1':[4,np.nan,7,np.nan,np.nan,9,5, np.nan , 1,9,np.nan, np.nan,np.nan, 5, np.nan], 'val2': [ np.nan, 5,7,np.nan, np.nan,8,3,np.nan, 4,np.nan, np.nan, np.nan,np.nan,21,np.nan]}) d = {'val1': {0: 4.0,1: 5.7142857142857144,2: 7.0,3: 5.7142857142857144,4: np.nan,5: 9.0,6: 5.0,7: np.nan,8: 1.0,9: 9.0,10: np.nan,11: np.nan,12: np.nan,13: 5.0,14: np.nan}, 'val2': {0: 8.0,1: 5.0,2: 7.0,3: 8.0,4: np.nan,5: 8.0,6: 3.0,7: np.nan,8: 4.0,9: np.nan,10: np.nan,11: np.nan,12: np.nan,13: 21.0,14: np.nan}} df_filled = pd.dataframe(d)
let's try this
df["val1"] = df["val1"].transform(lambda x: x.fillna(x.mean(), limit=2)) df["val2"] = df["val2"].transform(lambda x: x.fillna(x.mean(), limit=2)) print df
don't forget let know if solved problem :)
Comments
Post a Comment