I have a dataframe that contains two columns one is called hits:
0 NaN
1 5.0
2 NaN
3 5.0
4 NaN
...
295 NaN
296 NaN
297 NaN
298 NaN
299 NaN
and another column called converted:
0 0
1 0
2 0
3 0
4 0
..
345 0
346 1
347 0
348 1
349 0
what I want to do is to check if the row in the converted column has 0 or 1, if it has 0 the row in hits will have the value 6 ( it will replace the null value ) and if it has 1 it will replace the value with 9
I tried to use lambda but didnt give me a good result:
df['hits'] = df.apply(
lambda row: 9 if df['converted'] == 1 & df['hits'] == 'nan' else 6
,axis=1)
CodePudding user response:
You need change df
to local variable row
df['hits'] = df.apply(
lambda row: 9 if row['converted'] == 1 & pd.isnull(row['hits']) else 6
,axis=1)
Or with boolean masking
df.loc[df['converted'].eq(0) & df['hits'].isna(), 'hits'] = 6
df.loc[df['converted'].eq(1), 'hits'] = 9