I have a dataset, df, where there are several categories with number counts for each category. I would like to transform this set and show a distinct count for each category. I would also like to add a new 'count' column. The newly generated counts go off of the date column. Example how many distinct alphas are there in q1 for ID A: 2 and so on.
Data
ID date alpha beta gamma
A q1 2 2 1
B q1 2 2 3
C q1
D q2 2
Desired
ID type date count
A alpha q1 alpha1
A alpha q1 alpha2
A beta q1 beta1
A beta q1 beta2
A gamma q1 gamma1
B alpha q1 alpha1
B alpha q1 alpha2
B beta q1 beta1
B beta q1 beta2
B gamma q1 gamma1
B gamma q1 gamma2
B gamma q1 gamma3
C
D alpha q2 alpha1
D alpha q2 alpha2
Doing
I believe I may have to use the code below, in addition to the melt function.
df.melt(id_vars= ['ID', 'date'],
var_name = 'type',
value_name = 'count'
However, I am not able to expand the values into distinct counts
Any suggestions will be helpful. I am still researching this.