Multiplying columns with NULL values

Viewed 1606

I am trying to write a python code where I multiply a column value across the other columns. However, some values are NULL in my one C column. I am having a hard time how to program that if a value is NULL switch it to 1.

A     B     C         Result should be:    X    Y
5     3     2                              10   6
10    6                                    10   6
15    9                                    15   9
20    12    8                              160  96  

This is the python code I have tried:

if df[C] is NONE:
    df[X] = df[A]*1
else:
    df[X] = df[A]*df[C]

And so on with df[B] as well. But, it still gives me blanks in the excel rather than the "10 & 6" and "15 & 9" I need.

Results I get with my code:

X     Y
10    6


160   96
2 Answers

You can using np.where

df
Out[97]: 
    A   B    C
0   5   3  2.0
1  10   6  NaN
2  15   9  NaN
3  20  12  8.0
np.where(df.C.isna(),df.A,df.A*df.C)
Out[98]: array([ 10.,  10.,  15., 160.])

Your if function should with for loop

Just use fillna to replance NaNs with the value 1 in column C.

df['X'] = df['A'] * df['C'].fillna(1)
df['Y'] = df['B'] * df['C'].fillna(1)

>>> df
    A   B   C    X   Y
0   5   3   2   10   6
1  10   6 NaN   10   6
2  15   9 NaN   15   9
3  20  12   8  160  96
Related