我正在尝试创建一个累积条纹的计数,但可以由不同的列取消。在此计数中有三种结果
我尝试了几种不同的方法,尝试使用np.where组合标志和取消,使用where掩蔽groupby,多个累积和,填充和ngroup,但无法获得所需的结果。
df = pd.DataFrame(
{
"cond1": [True, False, True, False, True, False, True],
"cond2": [False, False, False, True, False, False, False]
})
df['flag'] = np.where(df['cond1'], 1, 0)
df['cancel'] = np.where(df['cond2'], 1, 0)
# Combined
df['combined'] = df['flag'] - df['cancel']
# Cumsum only
df['cumsum'] = df['combined'].cumsum()
# Cumcount masked by where
df['cumsum_cumcount'] = df.where(df['cond1']).groupby((df['cond2']).cumsum()).cumcount()
# Cumcount then cumsum
df['cumsum_cumcount_cumsum'] = df.where(df['cancel'] == False).groupby(df['flag'].cumsum()).cumcount().cumsum()
cond1 cond2 flag cancel c2 c3 c1
0 True False 1 0 0 0 1
1 False False 0 0 1 1 1
2 True False 1 0 2 1 2
3 False True 0 1 0 2 1
4 True False 1 0 1 2 2
5 False False 0 0 2 3 2
6 True False 1 0 3 3 3
cond1 cond2 streak
0 True False 1
1 False False 1
2 True False 2
3 False True 0
4 True False 1
5 False False 1
6 True False 2
7 True False 3
8 False False 3
9 True False 4
10 False True 0
11 False False 0
12 True False 1
当前条纹会重复,在cond1为true时累积,在cond2为false时重置。如果这可以在不太麻烦的情况下在相反的方向上积累,那么就会有很大的加分。取消为负值标志为正值。
发布于 2019-05-20 11:41:42
看起来您需要使用cumsum
和cond2
创建组密钥,然后使用cond1
使用cumsum
df.groupby(df.cond2.cumsum()).cond1.cumsum()
Out[155]:
0 1.0
1 1.0
2 2.0
3 0.0
4 1.0
5 1.0
6 2.0
7 3.0
8 3.0
9 4.0
10 0.0
11 0.0
12 1.0
Name: cond1, dtype: float64
https://stackoverflow.com/questions/56214022
复制相似问题