0

I have this dataframe:

df = pd.DataFrame(data=[[1,1],[1,2],[2,3],[2,4],[2,5],[2,6],[3,7],[3,8]],columns=['alarmId','attemptId'])

Which creates this table :

+---------+-----------+
| alarmId | attemptId |
+---------+-----------+
|       1 |         1 |
|       1 |         2 |
|       2 |         3 |
|       2 |         4 |
|       2 |         5 |
|       2 |         6 |
|       3 |         7 |
|       3 |         8 |
+---------+-----------+

I want to label the instance number of each attempts per alarm, such that it resulted in a table like this:

+---------+-----------+---------------+
| alarmId | attemptId | attemptNumber |
+---------+-----------+---------------+
|       1 |         1 |             1 |
|       1 |         2 |             2 |
|       2 |         3 |             1 |
|       2 |         4 |             2 |
|       2 |         5 |             3 |
|       2 |         6 |             4 |
|       3 |         7 |             1 |
|       3 |         8 |             2 |
+---------+-----------+---------------+

How can I do this?

sagungrp
  • 141
  • 1
  • 13

1 Answers1

2
df["attemptNumber"] = 1 + df.groupby("alarmId").cumcount()
print(df)

   alarmId  attemptId  attemptNumber
0        1          1              1
1        1          2              2
2        2          3              1
3        2          4              2
4        2          5              3
5        2          6              4
6        3          7              1
7        3          8              2
AMH
  • 502
  • 2
  • 10