I have a dataframe like as below
ID,design_id,year,output
1,21345,1978,1
1,3456,2019,1
1,5678,2021,1
1,7890,2021,1
1,5678,2021,2
1,1357,2020,3
2,9876,2021,8
2,9865,2021,1
2,9678,2021,0
I would like to do the below
a) create 4 year columns year_2019,year_2020,year_2021 and year_2022.
b) put the count of unique design_id for each ID under the respective year columns
I tried the below 2 approaches with the help of this post
pd.crosstab(
index=tf['ID'], columns=tf['year'],
values=tf['design_id'], aggfunc='nunique').fillna(0)
-------------------------------------
out = (pd
.crosstab(df['ID'], df['year'])
.reindex(range(2019, 2022+1), axis=1, fill_value=0)
.add_prefix('year_')
.reset_index()
.rename_axis(columns=None)
)
My real dataframe has 4 million rows and has 50 unique year values.(from 1970 to 2022)
But I want the count of unique design id (and not the count of records) for each ID under each year columns 2019,2020,2021 and 2022.
I expect my output to be like as below
ID,year_2019,year_2020,year_2021,year_2022
1,1,1,2,0
2,0,0,3,0