Home > Backend Development > Python Tutorial > How Can I Reshape a Pandas DataFrame from Wide to Long Format Using `pd.melt()`?

How Can I Reshape a Pandas DataFrame from Wide to Long Format Using `pd.melt()`?

Susan Sarandon
Release: 2024-12-22 14:43:14
Original
667 people have browsed it

How Can I Reshape a Pandas DataFrame from Wide to Long Format Using `pd.melt()`?

Convert Columns into Rows with Pandas

This question addresses the need to transform a CSV dataset where date-related information is distributed across multiple columns into a format where each date has its own row. To achieve this transformation, the user employs the pd.melt function.

The original CSV structure resembles:

location    name    Jan-2010    Feb-2010    March-2010
A           "test"  12          20          30
B           "foo"   18          20          25
Copy after login

The desired outcome is a table with columns location, name, Date, and Value:

location    name    Date        Value
A           "test"  Jan-2010    12       
A           "test"  Feb-2010    20
A           "test"  March-2010  30
B           "foo"   Jan-2010    18       
B           "foo"   Feb-2010    20
B           "foo"   March-2010  25
Copy after login

The pd.melt function provides the means to restructure the data. It takes several arguments:

  • id_vars: The columns that remain unchanged as the table is melted. In this case, location and name.
  • var_name: The name of the new column that will hold the original column names (as they were before melting). In this case, Date.
  • value_name: The name of the column that will hold the values from the original data columns. In this case, Value.
df.melt(id_vars=["location", "name"],
        var_name="Date",
        value_name="Value")
Copy after login

The resulting DataFrame matches the desired output, with each month now occupying a separate row.

The above is the detailed content of How Can I Reshape a Pandas DataFrame from Wide to Long Format Using `pd.melt()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template