Write a program in Python to count the records based on the designation in a given DataFrame

PythonPandasServer Side ProgrammingProgramming

Input

Assume, we have a DataFrame and group the records based on the designation is −

Designation
architect    1
programmer   2
scientist    2

Solution

To solve this, we will follow the below approaches.

  • Define a DataFrame

  • Apply groupby method for Designation column and calculate the count as defined below,

df.groupby(['Designation']).count()

Example

Let us see the following implementation to get a better understanding.

import pandas as pd
data = { 'Id':[1,2,3,4,5],
         'Designation':
['architect','scientist','programmer','scientist','programmer']}
df = pd.DataFrame(data)
print("DataFrame is\n",df)
print("groupby based on designation:")
print(df.groupby(['Designation']).count())

Output

Designation
architect    1
programmer   2
scientist    2
raja
Published on 11-Feb-2021 09:50:34
Advertisements