df['ratio'] = df.apply(lambda x: medians[x['department']] if pd.isnull(x['ratio']) or x['ratio']==0 else x['ratio'], axis=1)