Search code examples
pandasconditional-statementsdataframenanfill

change dataframe values based on next column value


I have the following problem to solve: Let's consider a Dataframe like:

df0:           A     B    C   
    2013-12-31 NaN  8    10
    2014-01-31 NaN  NaN  NaN  
    2014-02-28 NaN  NaN  NaN  

I want to fill with 0 column A only if the corresponding value in the column B is not 'NaN

df1:           A     B    C   
    2013-12-31 0     8    10
    2014-01-31 NaN  NaN  NaN  
    2014-02-28 NaN  NaN  NaN  

Solution

  • Use loc to find where column B values are not null:

    In [160]:
    
    df.loc[df.B.notnull(),'A']=0
    df
    Out[160]:
                 A   B   C
    2013-12-31   0   8  10
    2014-01-31 NaN NaN NaN
    2014-02-28 NaN NaN NaN
    
    [3 rows x 3 columns]