9951 explained code solutions for 126 technologies


python-pandasHow to aggregate (groupby) dataframe using count


import pandas as pd

data = pd.DataFrame({
  'Vendor': ['US', 'US', 'US', 'KR', 'KR'],
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Phone Price': [204, 304, 404, 405, 305]
})

res = data.groupby(['Vendor']).count()ctrl + c
import pandas as pd

load Pandas module

pd.DataFrame

creates Pandas DataFrame object

.groupby(

groups given dataframe by list of columns

Vendor

column to group dataframe by

.count()

calculate number of rows for grouped values

res

will contain aggregated dataframe


Usage example

import pandas as pd

data = pd.DataFrame({
  'Vendor': ['US', 'US', 'US', 'KR', 'KR'],
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Phone Price': [204, 304, 404, 405, 305]
})

res = data.groupby(['Vendor']).count()
print(res)
output
        Phone  Phone Price
Vendor                    
KR          2            2
US          3            3