1

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

1 Answer 1

1

I think here loops are not necessary use DataFrame.isna with convert to integers for True/False to 1/0 mapping:

df = df.isna().astype(int) 
print (df)

   Field_1  Field_2  Field_3
a        0        0        1
b        0        0        0
c        0        0        0
d        0        0        0
e        0        1        0
f        0        0        0
g        0        0        0

Your solution should be changed with axis=1 for loop per rows and for test scalars is used pandas.isna:

df = df.apply(lambda x: 1 if pd.isna(x['Field_2']) else 0, axis=1) 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.