Pandas column values to columns

Given a Pandas DataFrame, we have to explode column into multiple columns.
Submitted by Pranit Sharma, on July 21, 2022

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

Sometimes we perform some complex operations on our DataFrame to draw some complex but useful insights from the data. In that case, we sometimes need to explode a column/series into multiple columns of a pandas Dataframe.

Pandas column values to columns

To explode column into multiple columns, we will use pandas.DataFrame.pivot_table() method. This 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.

Syntax:

Syntax of the method is: [source]

DataFrame.pivot_table(
    values=None, 
    index=None, 
    columns=None, 
    aggfunc='mean', 
    fill_value=None, 
    margins=False, 
    dropna=True, 
    margins_name='All', 
    observed=False, 
    sort=True)
Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python program for Pandas column values to columns

# Importing pandas package
import pandas as pd

# Creating a Dictionary
d = {
    'id':[0,1,1,2,2],
    'One':['food','cloths','wood','food','cloths'],
    'Two':['oranges','bananas','apples','grapes','kiwis']
}

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

# Display DataFrame
print("Created DataFrame\n",df,"\n")

# Pivot dataframe
result = df.pivot_table(values='Two', index=df.index, columns='One', aggfunc='first')

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

Output

The output of the above program is:

Example: Pandas column values to columns

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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