![]() |
VOOZH | about |
In this article, we will GroupBy two columns and count the occurrences of each combination in Pandas. Grouping by elements means organizing data into subsets based on column values, like grouping all rows with the same "State" or "Product." After grouping, we can perform operations like counting, summarizing, or calculating values within each group.
DataFrame.groupby() method is used to separate the Pandas DataFrame into groups. It will generate the number of similar data counts present in a particular column of the data frame.
We will start by creating a simple DataFrame for demonstration purposes:
Output:
The size() method returns the total number of elements in a group. We can use groupby() followed by size() to count the occurrences of each combination of values in two columns.
Output:
Explanation:
count() function counts the non-NA/null values across a specified column or axis. It can be used to count occurrences based on any column.
Output:
Explanation:['Sale'].count() counts the non-null values in the 'Sale' column for each group of 'States' and 'Products'.
reset_index() method is used to reset the index of the DataFrame, converting the grouped data back into a normal DataFrame.
Output:
Explanation:
The pivot() function in Pandas is used to reshape data, creating a pivot table based on three columns.
Output:
Explanation:
Related Articles: