How to condition the loop for one column to fill another column values in pandas dataframe

Viewed 293

Here's the dataframe

enter image description here

I need is if Beat column value is Nan , it should be filled as 0 in the Disease column

if Beat column value is anything except Nan , it should be filled as 1 in the Disease column

What i have tried so far ,

if a['Beat'].value('NaN'):
    a['Disease'].fillna(0)
else:
    a['Disease'].fillna(1)

Also tried this

if a['Beat']=='NaN':
    a['Disease'].fillna(0)
else:
    a['Disease'].fillna(1)

Both of them didn't work for me.

2 Answers

Try with loc:

a['Disease'] = a['Disease'].fillna(0)
a.loc[a['Beat'].isna(), 'Disease'] = 1

Or try fillna:

a['Disease'] = a['Disease'].fillna(a['Beat'].notna().astype(int))

So you need 1 if not missing value else 0, so possible solutions are test not missing values by Series.notna and convert it to 0, 1:

#if possible `NaN` is string convert to missing values
a = a.replace('NaN', np.nan)

a['Disease'] = a['Beat'].notna().astype(int)

a['Disease'] = a['Beat'].notna().view('i1')

a['Disease'] = np.where(a['Beat'].notna(), 1, 0)

a['Disease'] = np.where(a['Beat'].isna(), 0, 1)

Sample:

a = pd.DataFrame({'Beat': [np.nan, 5, np.nan]})

#e.g. this solution, all working same
a['Disease'] = np.where(a['Beat'].isna(), 0, 1)
print (a)
   Beat  Disease
0   NaN        0
1   5.0        1
2   NaN        0
Related