Create a variable if another variable is null in python

Viewed 28

I would create a variable if another variable is null.

`

if df['var_1'].isnull():
     df['var_2']==1
else:
     df['var_2']==0

` I know, this code is not true, it is to make you understand the problem.

Can someone help me? Thanks

1 Answers

If this is pandas, we should try to stick to pandas/numpy for this type of thing.

# For your specific case:
df['var_2'] = df['var_1'].notna().astype(int)

# A more generalized approach:
df['var_2'] = np.where(df['var_1'].isna(), 'if true', 'if false')
Related