Pandas-以值是否大于0为条件将一列除以另一列? [英] Pandas- Dividing a column by another column conditional on if values are greater than 0?

查看:140
本文介绍了Pandas-以值是否大于0为条件将一列除以另一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框,其中包含日期,项目和2个值.我要做的就是输出另一列,如果B列大于0,则输出A列/B列的乘积;如果B列等于0,则输出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  

这是我编写的代码,但是内核一直在消亡(请记住,这只是一个示例表,我大约有30,000行,所以没有什么太疯狂了)

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.

推荐答案

您可以使用np.where

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

或者如果您想使用loc

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

,然后fillna(0)

这篇关于Pandas-以值是否大于0为条件将一列除以另一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆