Pandas: calculating values with .where() leaves rows blank

I'm using the following in an attempt to selectively apply calculations to parts of a dataframe. It seems as though when the second statement is run, the values from the first statement are removed.

df5['AbsWindVAspect'] = df5['tmpAbsWindAspect1'].where(df5['tmpAbsWindAspect1'] <= 180)
df5['AbsWindVAspect'] = df5['tmpAbsWindAspect2'].where(df5['tmpAbsWindAspect1'] > 180)

Is there a different approach I should be using here to identifying rows that meet a certain criteria, performing the calculation, then changing to other rows with new criteria?

Answers 1

  • I believe you want where with other option:

    df5['AbsWindVAspect'] = df5['tmpAbsWindAspect1'].where(df5['tmpAbsWindAspect1'] <= 180, 
                                                           df5['tmpAbsWindAspect2'])
    

    Or use np.where for somewhat more readable code:

    df5['AbsWindVAspect'] = np.where(df5['tmpAbsWindAspect1'] <= 180,
                                     df5['tmpAbsWindAspect1'],
                                     df5['tmpAbsWindAspect2']
                                    )
    

Related Articles