Skip to content
Advertisement

How to use pandas to create a column that stores count of first occurrences on a group-by?

Q1. Given data frame 1, I am trying to get group-by unique new occurrences & another column that gives me existing ID count per month

JavaScript

Expected output for unique newly added group-by ID values & for existing sum of ID values

JavaScript

Note: Mar-2020 ID_Count is ZERO because ID 1, 2, and 3 were present in previous months.

Note: Existing count is 0 for Jan-2020 because there were zero IDs before Jan. The existing count for Feb-2020 is 1 because before Feb there was only 1. Mar-2020 has 3 existing counts as it adds Jan + Feb and so on

Advertisement

Answer

I think you can do it like this:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement