Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

python - how to fill NA with mean only for 2 or less consequective values of NA

I am new to python. please help me how I should proceed. The following dataframe contains large blocks of NaNs. # Fill the NAs with mean only for 2 or less consecutive values of NAs. # Refer to the documentation of fillna() to find out the parameter you would use to fill only a certail number of NAs. # The resulting dataframe should look like df_filled

# The resulting dataframe should look like 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 to let us know if it solved your problem :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...