Reputation: 181
I need to create 'winning streak' columns. For example, I have data like below. The column having the maximum value is the winner.
AA BB CC
5.95 5.95 0
0 -2.35 2.35
-0.6 -0.6 -0.6
-2.35 2.35 0
-1.6 1.6 -1.6
-1.25 1.25 1.25
1.85 0 -1.85
1.3 0 -1.3
-1.7 1.7 -1.7
0 0.25 0.25
and need to create "winning streak; how many times win cosecutively" columns of each like below.
AA BB CC CW_AA CW_BB CW_CC
5.95 5.95 0 1 1 0
0 -2.35 2.35 0 0 1
-0.6 -0.6 -0.6 1 1 2
-2.35 2.35 0 0 2 0
-1.6 1.6 -1.6 0 3 0
-1.25 1.25 1.25 0 4 1
1.85 0 -1.85 1 0 0
1.3 0 -1.3 2 0 0
-1.7 1.7 -1.7 0 1 0
0 0.25 0.25 0 2 1
I've tried to make it using "itertools" library (groupby) but can't yet. Anyone could help me please?
pd.DataFrame({'AA':[5.95, 0, -0.6, -2.35, -1.6, -1.25, 1.85, 1.3, -1.7, 0],
'BB':[5.95, -2.35, -0.6, 2.35, 1.6, 1.25, 0, 0, 1.7, 0.25],
'CC':[0, 2.35, -0.6, 0, -1.6, 1.25, -1.85, -1.3, -1.7, 0.25]})
Upvotes: 1
Views: 281
Reputation: 863291
Use:
a = df.eq(df.max(axis=1), axis=0)
b = a.cumsum()
df = b - b.where(~a).ffill().fillna(0).astype(int)
print (df)
AA BB CC
0 1 1 0
1 0 0 1
2 1 1 2
3 0 2 0
4 0 3 0
5 0 4 1
6 1 0 0
7 2 0 0
8 0 1 0
9 0 2 1
Explanation:
eq
with max
per rowsTrue
s by subtract cumulative sums by cumsum
Upvotes: 5