-3

I have the following dataset :

SessionNo ItemNo  TransactType
1           12        0
1           13        1    
1           12        1
2           15        0
...

I want to generate a new attribute Time according to the SessionNo attribute. The new dataset looks like that :

SessionNo  Time  ItemNo  TransactType
    1        1    12        0
    1        2    13        1    
    1        3    12        1
    2        1    15        0
   ...

Is there a simple way to perform this task in Python?

martineau
  • 119,623
  • 25
  • 170
  • 301
Krukiou
  • 141
  • 12

1 Answers1

1

Seems like you want cumcount.

You will have to add 1 to the result to start the count at 1 instead of 0:

In [18]: df['Time'] = df.groupby('SessionNo').cumcount()+1

In [19]: df
Out[19]:
   SessionNo  ItemNo  TransactType  Time
0          1      12             0     1
1          1      13             1     2
2          1      12             1     3
3          2      15             0     1
user3483203
  • 50,081
  • 9
  • 65
  • 94
  • @Krukiou, Note: *attribute* is a term which has an [entirely different](https://stackoverflow.com/questions/49748749/where-is-the-value-when-i-do-this-in-pandas-series) meaning to *series*, even in the context of `pandas`. Here we assume, as per your desired output, that you want a new series. – jpp May 13 '18 at 23:24
  • Thanks for the answer : I didn't know the cumcount() function. – Krukiou May 13 '18 at 23:50