asd
asd

Reputation: 1309

None produced in loop

Why does this function return None if missing? I only want NaN when there is a missing value.

def func(row):
  if (pd.notna(row['year'])):
       if (pd.notna(row['fruit'])) & (pd.notna(row['signifiance'])):
          return row['fruit']
       elif (pd.isna(row['fruit'])) & (pd.notna(row['signifiance'])):
          return row['fruit']
  else:
       return np.NaN
df['new_col'] = df.apply(func, axis=1)
df  fruit   year  price  vol  signifiance
0   apple   2010  1      5    NaN
1   apple   2011  2      4    NaN
2   apple   2012  3      3    NaN
3   NaN     2013  3      3    NaN
4   NaN     NaN   NaN    3    NaN
5   apple   2015  3      3    important

Actual Output:

df  fruit   year price  vol  signifiance   new_col
0   apple   2010  1      5    NaN           None 
1   apple   2011  2      4    NaN           None
2   apple   2012  3      3    NaN           None
3   NaN     2013  3      3    NaN           None
4   NaN     NaN   NaN    3    NaN           None
5   apple   2015  3      3   important      apple

Expected Output:

df  fruit   year price  vol  signifiance   new_col
0   apple   2010  1      5    NaN           NaN
1   apple   2011  2      4    NaN           NaN
2   apple   2012  3      3    NaN           NaN
3   NaN     2013  3      3    NaN           NaN
4   NaN     NaN   NaN    3    NaN           NaN
5   apple   2015  3      3   important      apple

Upvotes: 0

Views: 43

Answers (1)

BENY
BENY

Reputation: 323226

Change to

def func(row):
  if (pd.notna(row['year'])):
       if (pd.notna(row['fruit'])) & (pd.notna(row['signifiance'])):
          return row['fruit']
       elif (pd.isna(row['fruit'])) & (pd.notna(row['signifiance'])):
          return row['fruit']
       else:
          return np.NaN
  else:
       return np.NaN
  
df.apply(func,axis=1)
Out[178]: 
0      NaN
1      NaN
2      NaN
3      NaN
4      NaN
5    apple
dtype: object

Upvotes: 1

Related Questions