Search code examples
pythonpandasdata-analysis

How do i count the number of similar values in a column in dataframe?


    #   Name    Type 1  Type 2  Total   HP  Attack  Defense  
1   Bulbasaur   Grass   Poison  318     45  49      65      
2   Ivysaur     Grass   Poison  405     60  62      80      
3   Venusaur    Grass   Poison  525     80  82      100     
4   Charmander  Fire    NaN     309     39  52      60      
5   Charmeleon  Fire    NaN     405     58  64      80  

I have a dataframe like the above. I need to calculate the number of 'Grass' type pokemons from 'Type 1'. How do i do that?


Solution

  • IIUC you need value_counts:

    df = df['Type 1'].value_counts()
    print (df)
    Grass    3
    Fire     2
    Name: Type 1, dtype: int64
    

    Or groupby with aggregating size:

    df = df.groupby(['Type 1']).size()
    print (df)
    Type 1
    Fire     2
    Grass    3
    dtype: int64