python - backward filling with condition -
i apply backward filling on particular column of dataframe following condition: have "colum_a" can assume 4 values, called a, b, c, d and, backward filling should work in following:
if first not nan a, backward_filling a; if first not nan b, backward_filling b; if first not nan c, backward_filling b; if first not nan d, backward_filling c; if column_a contains nan, backward_filling d
for example:
input df:
colum_a nan nan b b c c
output df:
colum_a b b c c d d
please, appreciated. best regards, carlo
i think need map
bfill
condition:
#get mask filling nans m = df['colum_a'].isnull() d = {'a':'a','b':'b','c':'b','d':'c'} #d if values nan df['colum_b'] = 'd' if m.all() else np.where(m, df['colum_a'].map(d).bfill(),df['colum_a']) #alternative #df['colum_b'] = 'd' if m.all() else df['colum_a'].mask(m, df['colum_a'].map(d).bfill()) print (df) colum_a colum_b 0 nan b 1 nan b 2 b b 3 4 nan b 5 c c 6 c c 7 nan c 8 nan c 9 nan c 10 d d 11 d d 12 13 c c 14 nan 15 16 nan nan
Comments
Post a Comment