![](/img/trans.png)
[英]Dropping rows if values from a column do not meet the requirements in another column
[英]Need help trying to reset cum sum value back to zero when criteria is not meet by comparing values in previous rows from another column
如果价格连续两次上涨,我正在尝试输入 1 或 Yes。 我尝试使用 cumsum,但如果它不正确,我无法弄清楚如何将值重置为零
df["Increased Twice?"] = ((df.shift(1)["Price Change"] == df3bet["Price Change"])).cumsum()
这是我拥有的代码的结果
ProductID Price Change Increased Twice?
2d3Q Increase 0
2d3Q Increase 1
2d3Q Decrease 1
2d3Q Increase 1
2d3Q Increase 2
2d3Q Decrease 2
2d3Q Increase 2
2d3Q Increase 3
这就是我要的
ProductID Price Change Increased Twice?
2d3Q Increase 0
2d3Q Increase 1
2d3Q Decrease 0
2d3Q Increase 0
2d3Q Increase 1
2d3Q Decrease 0
2d3Q Increase 0
2d3Q Increase 1
我也尝试了一些不同的 if then 语句,但我还没有开始工作。
让我们尝试,首先找到“增加”的位置,然后根据“减少”创建组,然后求和并检查 2 增加的计数。
df['Increased Twice?'] = ((df['Price Change'] == 'Increase')\
.groupby((df['Price Change'] == 'Decrease').cumsum())\
.cumsum() == 2).astype(int)
Output:
ProductID Price Change Increased Twice?
0 2d3Q Increase 0
1 2d3Q Increase 1
2 2d3Q Decrease 0
3 2d3Q Increase 0
4 2d3Q Increase 1
5 2d3Q Decrease 0
6 2d3Q Increase 0
7 2d3Q Increase 1
尝试numpy.where()
:
import numpy as np
df['Increased Twice?'] = np.where(df['Price Change'] == df.shift(1)['Price Change'], 1, 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.