Pandas - want to create new variable based on last occurrence of element in reference variable?

Viewed 41

I have a DataFrame:-

   col count
0  B   1
1  B   2
2  A   1 
3  A   2
4  A   3
5  C   1
6  C   2
7  C   3
8  C   4

wan to create new variable named Flag according to last occurrence of B , A in col variable. reference df:-

   col count  Flag
0  B   1      0
1  B   2      1 
2  A   1      0
3  A   2      0
4  A   3      1
5  C   1      0
6  C   2      0
7  C   3      0
8  C   4      1

TIA

1 Answers

Use Series.duplicated with numpy.where:

df['Flag'] = np.where(df['col'].duplicated(keep='last'), 0, 1)

Or Series.view with invert mask by ~:

df['Flag'] = (~df['col'].duplicated(keep='last')).view('i1')

print (df)
  col  count  Flag
0   B      1     0
1   B      2     1
2   A      1     0
3   A      2     0
4   A      3     1
5   C      1     0
6   C      2     0
7   C      3     0
8   C      4     1
Related