Home > Blockchain >  Calculate counts of unique values based on other column
Calculate counts of unique values based on other column

Time:11-20

First group with col1 then find the counts of unique item in col2, not the number of counts .value_counts not giving desired results

 df
      col1 col2
    1 A      x  
    2 A      y
    3 A      x
    3 B      x
    4 B      x
    5 c      x
    6 c      y
    7 c      z
    
    desired output
    
    A 2
    B 1
    c 3

CodePudding user response:

Use nunique:

df.groupby('col1')['col2'].nunique()

Output:

col1
A    2
B    1
c    3
Name: col2, dtype: int64

CodePudding user response:

Try this:

df.groupby(["col1"])["col2"].nunique()
  • Related