需要帮助尝试通过比较另一列中前几行中的值来尝试在不满足条件时将累计总和值重置回零
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 或“是”。我尝试使用 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 语句,但我还没有开始工作。
让我们试试,首先找到 'Increase' 的位置,然后根据 'Decrease' 创建组,然后求和并检查 2 个增加的计数。
df['Increased Twice?'] = ((df['Price Change'] == 'Increase')\
.groupby((df['Price Change'] == 'Decrease').cumsum())\
.cumsum() == 2).astype(int)
输出:
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)
如果价格连续两次上涨,我想输入 1 或“是”。我尝试使用 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 语句,但我还没有开始工作。
让我们试试,首先找到 'Increase' 的位置,然后根据 'Decrease' 创建组,然后求和并检查 2 个增加的计数。
df['Increased Twice?'] = ((df['Price Change'] == 'Increase')\
.groupby((df['Price Change'] == 'Decrease').cumsum())\
.cumsum() == 2).astype(int)
输出:
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)