# Pandas – Groupby value counts on the DataFrame

• Last Updated : 15 Mar, 2021

Prerequisites: Pandas

Pandas can be employed to count the frequency of each value in the data frame separately. Let’s see how to Groupby values count on the pandas dataframe. To count Groupby values in the pandas dataframe we are going to use groupby() size() and unstack() method.

### Functions Used:

• groupby(): groupby() function is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names

Syntax:

DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)

Parameters :

• by : mapping, function, str, or iterable
• axis : int, default 0
• level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels
• as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output
• sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group.
• group_keys : When calling apply, add group keys to index to identify pieces
• squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent type

Returns : GroupBy object

• size(): size method is used to get the integer representing the number of elements in object. The size method is return the number of rows times number of columns if DataFrame.

Syntax:

Dataframe.size()

• unstack(): unstack method works with the MultiIndex objects in DataFrame, producing a reshaped DataFrame with a new inner-most level of column labels.

Syntax:

Dataframe.unstack()

### Approach

• Import module
• Create data frame
• Count value of occurrences of each value
• Print resultant data frame

Example1:

## Python

 `# import pandas``import` `pandas as pd`` ` `# create dataframe``df ``=` `pd.DataFrame({``    ``'Course'``: [``'BBA'``, ``'BCA'``, ``'BBA'``, ``'BCA'``, ``'BCA'``],``    ``'Student Name'``: [``'Rishabh'``, ``'Rahul'``, ``'Suraj'``, ``'Mukul'``, ``'Vinit'``],``    ``'Age'``: [``21``, ``22``, ``23``, ``22``, ``23``]})`` ` ` ` `# print original dataframe``print``(``"original dataframe"``)``display(df)`` ` `# counts Groupby value``df ``=` `df.groupby([``'Course'``, ``'Student Name'``, ``'Age'``]).size().unstack(fill_value``=``0``)`` ` `# print dataframe``print``(``"Result :"``)``display(df)`

Output: Example 2:

## Python

 `# import pandas``import` `pandas as pd`` ` `# create dataframe``df ``=` `pd.DataFrame({``    ``'City'``: [``'Saharanpur'``, ``'Meerut'``, ``'Saharanpur'``, ``'Saharanpur'``, ``'Meerut'``],``    ``'Employes Name'``: [``'Robin'``, ``'Tushar'``, ``'Rohan'``, ``'Mukul'``, ``'Manoj'``],``    ``'Salary'``: [``21000``, ``22000``, ``21000``, ``22000``, ``22000``]})`` ` ` ` `# print original dataframe``print``(``"original dataframe: "``)``display(df)`` ` `# counts Groupby value``df ``=` `df.groupby([``'City'``, ``'Employes Name'``, ``'Salary'``]``                ``).size().unstack(fill_value``=``0``)`` ` `# print dataframe``print``(``"result: "``)``display(df)`

Output: My Personal Notes arrow_drop_up
{"ft_lang_label":"__label__en","ft_lang_prob":0.55013657,"math_prob":0.81568336,"size":3042,"snap":"2022-27-2022-33","text_gpt3_token_len":800,"char_repetition_ratio":0.12343647,"word_repetition_ratio":0.09090909,"special_character_ratio":0.28106508,"punctuation_ratio":0.19109462,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9908638,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,4,null,4,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-07-02T21:09:12Z\",\"WARC-Record-ID\":\"<urn:uuid:a5b03020-2298-44b0-a549-ae75f3c69e9f>\",\"Content-Length\":\"134244\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:58dbc0f1-3f0f-4a2a-8112-39801de75e3b>\",\"WARC-Concurrent-To\":\"<urn:uuid:3e1ff914-4c7b-4732-be5c-ec078835ba9c>\",\"WARC-IP-Address\":\"23.62.230.138\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/pandas-groupby-value-counts-on-the-dataframe/?ref=rp\",\"WARC-Payload-Digest\":\"sha1:6MH57L5RUMWS2TZPYZW4YRTRYI2EBS63\",\"WARC-Block-Digest\":\"sha1:JZMUGJPDKOWYI7WO6XKPDX2MFPJBRJON\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-27/CC-MAIN-2022-27_segments_1656104204514.62_warc_CC-MAIN-20220702192528-20220702222528-00190.warc.gz\"}"}