I'd like to replace every NaN value in my data frame with a 1 and every other value with a 0. It's just an example for a project where I need to change the df depending on the NaN value in one column.
I tried isnull(), isnan(), x.Field_2 and many more variations. Also the documentation of isnull didn't really help me. I googled a lot and only found operations where I can get all NaN values of a df.
I guess the problem is that x['Field_2'].isnull() is returning an array but I couldn't think of something else that would change the df. Basically I'm searching for a a way to check for every row if the cell is NaN and execute it for every cell.
My error message:
KeyError: 'Field_2'
# importing pandas and numpy libraries
import pandas as pd
import numpy as np
# creating and initializing a nested list
values_list = [[15, 2.5, np.nan], [20, 4.5, 50], [25, 5.2, 80],
[45, 5.8, 48], [40, np.nan, 70], [41, 6.4, 90],
[51, 2.3, 111]]
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=['Field_1', 'Field_2', 'Field_3'],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
df = df.apply(lambda x: 1 if x['Field_2'].isnull() else 0)
--------- solution
Through your help I could solve my problem. Thanks a lot! - final solution:
resultList = df.apply(lambda x: x['Field_1'] if pd.isna(x['Field_2']) else x['Field_2'], axis=1)
df['newColumn'] = resultList
df