pandas equivalent of np.where

后端 未结 1 1930
野趣味
野趣味 2020-11-28 06:43

np.where has the semantics of a vectorized if/else (similar to Apache Spark\'s when/otherwise DataFrame method). I know that I can use

相关标签:
1条回答
  • 2020-11-28 07:27

    Try:

    (df['A'] + df['B']).where((df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
    

    The difference between the numpy where and DataFrame where is that the default values are supplied by the DataFrame that the where method is being called on (docs).

    I.e.

    np.where(m, A, B)
    

    is roughly equivalent to

    A.where(m, B)
    

    If you wanted a similar call signature using pandas, you could take advantage of the way method calls work in Python:

    pd.DataFrame.where(cond=(df['A'] < 0) | (df['B'] > 0), self=df['A'] + df['B'], other=df['A'] / df['B'])
    

    or without kwargs (Note: that the positional order of arguments is different from the numpy where argument order):

    pd.DataFrame.where(df['A'] + df['B'], (df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
    
    0 讨论(0)
提交回复
热议问题