Pandas pivot table count frequency in one column

Given a pandas dataframe, we have to count frequency values in one column which is linked to another values. By Pranit Sharma Last updated : October 03, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Pivot table count frequency in one column

For this purpose, we will use the pivot_table method inside which we will set a parameter aggfunc = len so that it counts the number of values. The pandas.DataFrame.pivot() method is used to reshape the given DataFrame according to index and column values. It is used when we have multiple items in a column, we can reshape the DataFrame in such a way that all the multiple values fall under one single index or row, similarly, we can convert these multiple values as columns.

Let us understand with the help of an example,

Python program for pandas pivot table count frequency in one column

# Importing pandas package
import pandas as pd

# Ipporting numpy package
import numpy as np

# Creating a dictionary
d = {
    'Roll_number':[100,100,200,200,200,300,300],
    'Grades':['A', 'A', 'A', 'B', 'B','A', 'B']
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Pivoting the result
res = df.pivot_table(index='Roll_number', columns='Grades', aggfunc=len, fill_value=0)

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Pandas pivot table count frequency in one column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.