Home > OS >  pandas merge how to set default Nan to 0 when result not match
pandas merge how to set default Nan to 0 when result not match

Time:09-30

I'm merging 2 dfs,df1 and df2,while not matching, the result will be Nan, but I need it default to 0.

df1 = pd.merge(df1, df2, left_on='MortTab', right_on='MortTab', how='left',suffixes=(' ', ''))

Now I use this way to convert the Nan to 0:

for i in ['col1','col2','col3']: #columns that I want to check the values are NaN or not
    df1[i] = np.where(df1[i].isnull(), 0, df_ia[i])  #if it's NaN, convert it to 0,or keep the same

I manually looping each column value to check,if the value is NaN ,if yes,convert it to 0 ,if no keep the same.

Is the any better way to do that?

CodePudding user response:

You can use fillna() likewise:

df[['col1','col2','col3']].fillna(0, inplace = True) 

You can even fill specific values in specific columns using a dict likewise:

df.fillna({'col1':0 , 'col2':5, 'col3': 999}, inplace=True)

CodePudding user response:

df_1_cols_before = list(df_1)
df_1 = pd.merge(df_1, df_1, left_on='MortTab', right_on='MortTab', how='left',suffixes=(' ', ''))
df_1_cols_after = list(df_1)

fill_cols = list(set(df_1_cols_after)-set(df_1_cols_before))
df_1[fill_cols] = df_1[fill_cols].apply(lambda x: x.fillna(0))
  • Related