Lazy loaded image
🧧How to Convert Rows to Columns and Columns to Rows in Pandas DataFrame using Python?
Words 254Read Time 1 min
Mar 12, 2024
Aug 6, 2025

How to Convert Rows to Columns and Columns to Rows in Pandas DataFrame using Python?

type
status
date
slug
summary
tags
category
icon

Introduction

In Python, you can use the pandas library to work with tabular data, and the core data type in pandas is the DataFrame. Sometimes, when working with DataFrame data, you may need to convert rows to columns or columns to rows. Here is a simple example demonstrating how to achieve this using the pandas library.

Create Table

First, let’s create a new example DataFrame.

Convert Rows to Columns

In the code above, we simply use the melt function to transform each student's subject grades into a column, which gives us the following output.

Convert Columns to Rows

Column to row transformation, also known as data unpivoting, can be achieved using the pivot function in the pandas library. Here is an example code:
 
上一篇
How to read and write JSON files in Python
下一篇
Power BI: How to Create Dynamic Show Hide Slicer Panel

Comments
Loading...