Aggregation of fields is one of the basic necessity for data analysis and data science. Python’s Pandas module provide easy ways to do aggregation and calculate metrics. Finding distinct count value for each group can also be achieved while doing the group by. The function that is helpful for finding the distinct count value is nunique(). The below article explains with the help of an example How to calculate distinct count value by Group in Python.
John has store sales data available for analysis. There are five columns present in the data, Geography (country of store), Department (Industry category of the store), StoreID (Unique ID of each store), Time Period (Month of sales), Revenue (Total Sales for the month). John is looking forward to calculate distinct count of stores for each department. As there are duplicates in Store ID due to multiple rows for each store, unique or distinct count will be needed.
Find Total Number of Stores in Each Department
Step 1: Firstly, Import all the necessary modules.
import pandas as pd
Step 2: Use nunique() function along with groupby operation. As we are looking forward to group by each Department, by=”Department” works as groupby parameter. The StoreID field contains the ID of each store. To find the distinct count value, we will be using “StoreID” for distinct count value calculation. For the current example, syntax is:
df1.groupby(by="Department")["StoreID"].nunique()
Example 2: Calculate Total Number of Stores for Each Geograpphy
Here we are looking forward to calculate the distinct count value across each Geography. So, the field in groupby operation will be “Geography”
df1.groupby(by="Geography")["StoreID"].nunique()
Thus, John is able to calculate values as per his requirement in Python.
To get top certifications in Python and build your resume visit here. Also, you can read books listed here to build strong knowledge around Python.
Visit us below for video tutorial:
π¬ Stay Ahead in Data Science & AI β Subscribe to Newsletter!
π― Interview Series: Curated questions and answers for freshers and experienced candidates.
π Data Science for All: Simplified articles on key concepts, accessible to all levels.
π€ Generative AI for All: Easy explanations on Generative AI trends transforming industries.
π‘ Why Subscribe? Gain expert insights, stay ahead of trends, and prepare with confidence for your next interview.
10 thoughts on “How to count distinct by group in Python”
naturally like your web-site but you need to check the spelling on several of your posts. Several of them are rife with spelling issues and I find it very bothersome to tell the truth nevertheless Iζ£l certainly come back again.
I like what you guys are up also. Such intelligent work and reporting! Keep up the excellent works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my site π
Hi! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My blog looks weird when viewing from my iphone. I’m trying to find a template or plugin that might be able to fix this problem. If you have any suggestions, please share. Thank you!
Oh my goodness! a tremendous article dude. Thank you Nevertheless I’m experiencing difficulty with ur rss . Donζ° know why Unable to subscribe to it. Is there anybody getting identical rss downside? Anybody who is aware of kindly respond. Thnkx
Thanks for this excellent article. One other thing is that the majority of digital cameras come equipped with a new zoom lens so that more or less of your scene for being included through ‘zooming’ in and out. All these changes in focus length are reflected inside viewfinder and on huge display screen right at the back of the specific camera.
I think that a property foreclosure can have a important effect on the client’s life. Foreclosures can have a Six to several years negative effect on a borrower’s credit report. The borrower who’s applied for a mortgage or any loans for instance, knows that your worse credit rating is definitely, the more challenging it is to secure a decent loan. In addition, it could possibly affect a new borrower’s chance to find a quality place to let or rent, if that gets the alternative homes solution. Interesting blog post.
I want to show thanks to you just for rescuing me from this type of challenge. Right after browsing through the search engines and getting recommendations that were not pleasant, I assumed my life was done. Living minus the approaches to the difficulties you have solved by way of your main write-up is a serious case, and the kind which might have in a wrong way affected my entire career if I had not encountered your blog. Your primary natural talent and kindness in handling the whole lot was important. I am not sure what I would’ve done if I had not encountered such a stuff like this. I’m able to at this time look ahead to my future. Thanks very much for this skilled and effective guide. I won’t be reluctant to endorse your blog to any individual who needs guidance about this matter.
Amazing blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog stand out. Please let me know where you got your theme. Thanks
I know this if off topic but I’m looking into starting my own weblog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100 certain. Any tips or advice would be greatly appreciated. Kudos
It’s appropriate time to make some plans for the future and it is time to be happy. I have read this post and if I could I wish to suggest you few interesting things or tips. Maybe you can write next articles referring to this article. I want to read more things about it!
naturally like your web-site but you need to check the spelling on several of your posts. Several of them are rife with spelling issues and I find it very bothersome to tell the truth nevertheless Iζ£l certainly come back again.
I like what you guys are up also. Such intelligent work and reporting! Keep up the excellent works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my site π
Hi! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My blog looks weird when viewing from my iphone. I’m trying to find a template or plugin that might be able to fix this problem. If you have any suggestions, please share. Thank you!
Oh my goodness! a tremendous article dude. Thank you Nevertheless I’m experiencing difficulty with ur rss . Donζ° know why Unable to subscribe to it. Is there anybody getting identical rss downside? Anybody who is aware of kindly respond. Thnkx
Thanks for this excellent article. One other thing is that the majority of digital cameras come equipped with a new zoom lens so that more or less of your scene for being included through ‘zooming’ in and out. All these changes in focus length are reflected inside viewfinder and on huge display screen right at the back of the specific camera.
I think that a property foreclosure can have a important effect on the client’s life. Foreclosures can have a Six to several years negative effect on a borrower’s credit report. The borrower who’s applied for a mortgage or any loans for instance, knows that your worse credit rating is definitely, the more challenging it is to secure a decent loan. In addition, it could possibly affect a new borrower’s chance to find a quality place to let or rent, if that gets the alternative homes solution. Interesting blog post.
I want to show thanks to you just for rescuing me from this type of challenge. Right after browsing through the search engines and getting recommendations that were not pleasant, I assumed my life was done. Living minus the approaches to the difficulties you have solved by way of your main write-up is a serious case, and the kind which might have in a wrong way affected my entire career if I had not encountered your blog. Your primary natural talent and kindness in handling the whole lot was important. I am not sure what I would’ve done if I had not encountered such a stuff like this. I’m able to at this time look ahead to my future. Thanks very much for this skilled and effective guide. I won’t be reluctant to endorse your blog to any individual who needs guidance about this matter.
Amazing blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog stand out. Please let me know where you got your theme. Thanks
I know this if off topic but I’m looking into starting my own weblog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100 certain. Any tips or advice would be greatly appreciated. Kudos
It’s appropriate time to make some plans for the future and it is time to be happy. I have read this post and if I could I wish to suggest you few interesting things or tips. Maybe you can write next articles referring to this article. I want to read more things about it!