How to divide on Zero in Pandas Dataframe and make 1 column out of 2

I did spend few hours on Google but was not able to find solution for my issue. I'm receiving dataframe like this:

col1         col2     col3 
2022-03-01   234       0
2022-03-01   342       67
2022-03-01   0         0
2022-03-01   0         23

I need to divide Col2 on Col3 and result should look like this:

col1         col4 
2022-03-01   0      
2022-03-01   5.1
2022-03-01   0        
2022-03-01   0 

How I can do that ?? With functions like divide or / I'm always getting error: decimal./DivizionByZero

I did try to find any solution but in Google there is always basic stuff, like divide just number on number, not on Zero etc.

Thank you,

1 answer

  • answered 2022-05-04 10:24 jezrael

    If no decimals replace infinite values to 0 and then missing values:

    import numpy as np
    
    df['col4'] = df['col2'].div(df['col3']).replace(np.inf,0).fillna(0)
    print (df)
             col1  col2  col3      col4
    0  2022-03-01   234     0  0.000000
    1  2022-03-01   342    67  5.104478
    2  2022-03-01     0     0  0.000000
    3  2022-03-01     0    23  0.000000
    

    Solution with decimals:

    If possible convert to integers:

    df['col4'] = df['col2'].astype(int).div(df['col3'].astype(int)).replace(np.inf,0).fillna(0)
    print (df)
             col1 col2 col3      col4
    0  2022-03-01  234    0  0.000000
    1  2022-03-01  342   67  5.104478
    2  2022-03-01    0    0  0.000000
    3  2022-03-01    0   23  0.000000
    

    If not, replace 0 to 1 and then set 0 if at least in one column is 0:

    df['col4'] = df['col2'].div(df['col3'].replace(0, 1)).mask(df[['col2', 'col3']].eq(0).any(1), 0)
    print (df)
             col1 col2 col3                           col4
    0  2022-03-01  234    0                              0
    1  2022-03-01  342   67  5.104477611940298507462686567
    2  2022-03-01    0    0                              0
    3  2022-03-01    0   23                              0
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum