Pandas - make new column with 2 classes where last row by id is another class

Viewed 84

I have Data Frame with IDs in the first column and number of cycle in second.

Here's an example of what it looks like:

df2 = pd.DataFrame(np.array([[1, 1], [1, 2], [2, 1], [2, 2], [2, 3]]),
               columns=['ID', 'cycle'])

ID    cycle    
1     1         
1     2        
2     1       
2     2
2     3

I want to make new column with 2 classes: 'last cycle', 'not last cycle':

ID    cycle  group   
1     1        0 
1     2        1
2     1        0
2     2        0
2     3        1

How to solve this task?

Thanks in advance for replies

2 Answers

Many ways to do this.

One is to usegroupby.tail(1).index

df2.loc[df2.groupby('ID').cycle.tail(1).index, 'group'] = 1
df2.fillna(0)

ID    cycle  group   
1     1        0 
1     2        1
2     1        0
2     2        0
2     3        1

Let us do transform with last

df2['group']=df2.cycle.eq(df2.groupby('ID').cycle.transform('last')).astype(int)
df2
Out[244]: 
   ID  cycle  group
0   1      1      0
1   1      2      1
2   2      1      0
3   2      2      0
4   2      3      1
Related