Pandas- Dividing a column by another column conditional on if values are greater than 0?

后端 未结 2 1047
北恋
北恋 2021-01-05 08:51

I have a pandas dataframe that contains dates, items, and 2 values. All I\'m looking to do is output another column that is the product of column A / column B if column B is

相关标签:
2条回答
  • 2021-01-05 09:22

    You get that using np.where

    df['C'] = np.round(np.where(df['B'] > 0, df['A']/df['B'], 0), 1)
    

    Or if you want to use loc

    df.loc[df['B'] > 0, 'C'] = df['A']/df['B']
    

    and then fillna(0)

    0 讨论(0)
  • 2021-01-05 09:41

    Option 1
    You use pd.Series.mask to hide zeros, and then just empty cells with fillna.

    v = (df.A / df.B.mask(df.B == 0)).fillna(0)
    v
    
    0     0.000000
    1     0.000000
    2     2.500000
    3     4.000000
    4     1.000000
    5     0.000000
    6     1.000000
    7     1.000000
    8     0.333333
    9     0.000000
    10    1.666667
    11    0.000000
    dtype: float64
    
    df['C'] = v
    

    Alternatively, replace those zeros with np.inf, because x / inf = 0.

    df['C'] = (df.A / df.B.mask(df.B == 0, np.inf))
    

    Option 2
    Direct replacement with df.replace

    df.A / df.B.replace(0, np.inf)
    
    0     0.000000
    1     0.000000
    2     2.500000
    3     4.000000
    4     1.000000
    5     0.000000
    6     1.000000
    7     1.000000
    8     0.333333
    9     0.000000
    10    1.666667
    11    0.000000
    dtype: float64
    

    Keep in mind, you can do an astype conversion, if you want mixed integers and floats as your result:

    df.A.div(df.B.replace(0, np.inf)).astype(object)
    
    0            0
    1            0
    2          2.5
    3            4
    4            1
    5            0
    6            1
    7            1
    8     0.333333
    9            0
    10     1.66667
    11           0
    dtype: object
    
    0 讨论(0)
提交回复
热议问题