Pandas: DataFrame stack multiple column values into single column

Learn, how to stack multiple column values into single column?
By Pranit Sharma Last updated : September 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 the dataframe containing two columns each of which has repeating values, we need to figure out how to count by the number of rows for unique pair of columns.

DataFrame stack multiple column values into single column

For this purpose, you can use DataFrame.melt() method by defining the value_name of the new column, you can also drop a column by using the .drop() method along with. The DataFrame.melt() method unpivots a DataFrame from wide to long format, optionally leaving identifiers set.

Let us understand with the help of an example,

Python program for dataframe stack multiple column values into single column

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'subject.Maths':[70,67],
    'subject.Physics':[87,56],
    'subject.Chemistry':[76,86],
    'Students':['A','B']
}

# Creating a DataFrame
df = pd.DataFrame(d)

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

# Using melt method
keys = [c for c in df if c.startswith('subject.')]
res = df.melt('Students', value_name='keys').drop('variable', 1)

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

Output

The output of the above program is:

Example: Pandas: DataFrame stack multiple column values into single column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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