Pandas pivot tables row subtotals

Given a pandas dataframe, we have to pivot table's row subtotals. 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.

Problem statement

Suppose we are given a DataFrame of some products with their store address and their sales and we need to find the subtotal that is total sales of specific stores and then pivot the result.

Pivot table's row subtotals

For this purpose, we will use the pd.pivot_table() method inside which we will set a parameter aggfunc = np.sum to calculate summed values.

The pd.pivot_table() method 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 pivot table's row subtotals

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'state':['MH','GJ','HR','MH','MP'],
    'store':['pune','surat','gurugram','nasik','bhopal'],
    'sales':[190121,108380,201212,103901,132121]
}

# Creating DataFrame
df = pd.DataFrame(d)

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

# Pivoting the result
res = pd.pivot_table(df, values=['sales'],index=['state'], columns=['store'], aggfunc=np.sum, margins=True)

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

Output

The output of the above program is:

Example: Pandas pivot tables row subtotals

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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