Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 greater than 0, and 0 if column B is equal to 0.

   date     item   A   B        C       
 1/1/2017   a      0   3             0  
 1/1/2017   b      2   0             0  
 1/1/2017   c      5   2           2.5  
 1/1/2017   d      4   1             4  
 1/1/2017   e      3   3             1  
 1/1/2017   f      0   4             0  
 1/2/2017   a      3   3             1  
 1/2/2017   b      2   2             1  
 1/2/2017   c      3   9   0.333333333  
 1/2/2017   d      4   0             0  
 1/2/2017   e      5   3   1.666666667  
 1/2/2017   f      3   0             0  

this is the code I've written, but the kernel keeps dying (keep in mind this is just an example table, I have about 30,000 rows so nothing too crazy)

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

any idea on what's going on? Is something running infinitely that's causing it to crash? Thanks for the help.

like image 687
Dick Thompson Avatar asked Nov 21 '17 23:11

Dick Thompson


1 Answers

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)

like image 114
Vaishali Avatar answered Sep 24 '22 16:09

Vaishali