python pandas groupby the unique combination to find the total sum

Question:

I have dataframe as below

# initialize list of lists
data = [['A','1','US'], ['A','2','US'],['A','1','US'],['B','3','IN'],['B','3','IN'],['C','1','US']]
  
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['System','Number','Country'])

I need to find each Country total rows after getting the unique combination of the ‘System’ and ‘Number’

The required output is as below

Country count
US 3
IN 1

I tried the below to get the unique combination of the ‘system’ and ‘Number’ rows but not sure how to get them added to get the above country results

df.groupby(['System','Number'])['Country'].nunique()

Please help

Asked By: John

||

Answers:

Try this one

df.drop_duplicates(['System', 'Number']).groupby('Country').agg(Count = ('Country','count')).reset_index()
Answered By: nabilahnran

This is a typical use case for df.value_counts():

df.drop_duplicates(subset=['System', 'Number']).value_counts('Country')
Answered By: Erik Fubel

df.drop_duplicates().groupby(‘Country’)[[‘Country’]].count()

Answered By: Sajil Alakkalakath
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.