How to create 0 or 1 if value is the first occurrence and appearing in the latest year in pandas

I have a data frame where I need to create new column with 0 and 1 based on the new occurrence of column value.

Data frame input:

df = pd.DataFrame({'value_text': ['type1', 'type1', 'type1','type2','type2','type3','type3','type4','type4','type5','type6'],
                   'year': [2016,2017,2021,2018,2021,2019,2021,2020,2021,2021,2021]})


     value_text  year
0       type1  2016
1       type1  2017
2       type1  2021
3       type2  2018
4       type2  2021
5       type3  2019
6       type3  2021
7       type4  2020
8       type4  2021
9       type5  2021
10      type6  2021

Based on this need to create new column with 0 and 1 considering value_text that appeared only one time that too in the current year.

here in the result data frame type5 is appeared only in current year and didn’t appeared in previous years. basically trying to identify new occurrence and creating value 1 else 0.

Result:

df1 = pd.DataFrame({'value_text': ['type1', 'type1', 'type1','type2','type2','type3','type3','type4','type4','type5','type6'],
                   'year': [2016,2017,2021,2018,2021,2019,2021,2020,2021,2021,2021],
                   'value': [0, 0, 0,0,0,0,0,0,0,1,1]})

output:

     value_text  year  value
0       type1  2016      0
1       type1  2017      0
2       type1  2021      0
3       type2  2018      0
4       type2  2021      0
5       type3  2019      0
6       type3  2021      0
7       type4  2020      0
8       type4  2021      0
9       type5  2021      1
10      type6  2021      1

Answer

We can use duplicated to create a boolean mask m1 to identify the values which are not duplicated. Similarly, create another boolean mask m2 by comparing the year column with the current year, now take the logical and of m1 and m2 and assign the result to column value

m1 = ~df['value_text'].duplicated()
m2 = df['year'].eq(pd.Timestamp('now').year)
df['value'] = (m1 & m2).view('i1')

>>> df

   value_text  year  value
0       type1  2016      0
1       type1  2017      0
2       type1  2021      0
3       type2  2018      0
4       type2  2021      0
5       type3  2019      0
6       type3  2021      0
7       type4  2020      0
8       type4  2021      0
9       type5  2021      1
10      type6  2021      1