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
- Author:Luca Liu
- URL:http://www.blog.luca-liu.com/article/how-to-convert-rows-to-columns-and-columns-to-rows-in-pandas-dataframe-using-python
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!