Stack Exchange
Pandas Count no of Ids per month from the dataframe
I have a dataframe of users who performs certain task no of times in a month. I have sort of this data. (Cant share real data, so generated a dummy df as below)
df = pd.DataFrame(np.random.randint(1, 12,size=(100, 2)), columns=list('AB'))
df['Month'] = df.apply(lambda x: f"{x['A']}-2020", axis=1)
df['id'] = "UID"+ df['B'].astype(str)
df = df.drop(columns=['A', 'B'])
df.head(10)

Which would appear as below:
    Month   id
0   4-2020  UID3
1   5-2020  UID8
2   9-2020  UID3
3   5-2020  UID6
4   8-2020  UID7
5   8-2020  UID5
6   7-2020  UID11
7   10-2020 UID5
8   1-2020  UID10
9   4-2020  UID6

I want to find out no. of UIDs per month irrespective of which id it is. 
df.groupby(["Month", "id"]).size().reset_index(name='Count')

eg. it shoud show- 
   Month   id  
 '1-2020'  3 
 '2-2020'  5
 '3-2020'  n
 ...

Similarly for all months of the year. Not sure how to do the grouping

You can use pandas.DataFrame.groupby() in combination with pandas.DataFrame.nunique().
The code is following:
df.groupby('Month').id.nunique().reset_index()

The result will look like this:
      Month  id
0    1-2020  10
1   10-2020   7
2   11-2020   7
3    2-2020   5
4    3-2020   7
5    4-2020   5
6    5-2020   4
7    6-2020   7
8    7-2020   5
9    8-2020   7
10   9-2020   7


grouping by both Month and id and then applying .id.nunique() is always going to result in the value being 1 - you only want to group by Month...

Thank you for the comment. You are right. I edited my answer.

if you want the above mentioned output:
df.groupby("Month")['id'].nunique()

