Melt the Upper Triangular Matrix of a Pandas DataFrame

Learn, how to melt the upper triangular matrix of a pandas dataframe in Python? By Pranit Sharma Last updated : October 06, 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 that we are given square pandas dataframe, we need to melt the upper triangular matrix of this dataframe.

Melting the Upper Triangular Matrix of a Pandas DataFrame

For this purpose, we will first convert lower values of the dataframe to nan by using where and numpy.triu() and then we will use stack and reset_index() to melt the upper part of dataframe.

Let us understand with the help of an example,

Python program to melt the upper triangular matrix of a pandas dataframe

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating a dataframe
df = pd.DataFrame({'A':[1,5,10],'B':[2,7,12],'C':[3,8,13]})

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

# Converting lower values of df to nan
df = df.where(np.triu(np.ones(df.shape)).astype(np.bool_))

# Melting upper part
df = df.stack().reset_index()
df.columns = ['X','Y','Z']

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

Output

The output of the above program is:

Example: Melt the Upper Triangular Matrix of a Pandas DataFrame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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