• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How to count elements in a one to many relationship dataframe in python

Resolved: How to count elements in a one to many relationship dataframe in python

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

i have a dataframe which contains a client code, the number of the contract and the products from the contract.
Something like this :
client_code contract_number product
AAAA 1000 Water
AAAA 1000 Soda
AAAA 1000 Food
BACD 1001 Water
BACD 1001 Soda
DAMR 1002 Food

And I want to add a column which contains a count to see how many products are on a contract from 1 to n . Something like this:
client_code contract_number product count
AAAA 1000 Water 1
AAAA 1000 Soda 2
AAAA 1000 Food 3
BACD 1001 Water 1
BACD 1001 Soda 2
DAMR 1002 Food 1

I’ve tried with a for loop but it’s too slow ( like an hour ).
Any ideea how to speed up my code ?
PS : My data frame contains 500.000 lines .
Thank you !

Answer:

IIUC, you want a cumulative count by each client_code (or probably contract_number) – you can do that with the cumcount function:
Output

If you have better answer, please add a comment about this, thank you!

pandas python
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: navigate and redirect not redirecting to path in react router

24/03/2023

Resolved: Time Complexity: Find the number of people who know a secret leetcode 2327

24/03/2023

Resolved: Best way to create 3d matrix of variables in PULP

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.