Home > Backend Development > Python Tutorial > How to Convert a Long Pandas DataFrame to Wide Format Using the Pivot Method?

How to Convert a Long Pandas DataFrame to Wide Format Using the Pivot Method?

Barbara Streisand
Release: 2024-10-28 17:50:02
Original
254 people have browsed it

How to Convert a Long Pandas DataFrame to Wide Format Using the Pivot Method?

Pandas Reshaping: Converting Long to Wide Format

When working with tabular data, it is often necessary to reshape it from long to wide format. While Pandas provides functions like melt and stack, they may not be sufficient for complex reshaping scenarios.

In the provided context, we have a long dataset with columns including 'Salesman', 'Height', 'product', and 'price.' The goal is to reshape it into a wide format with three additional columns: 'product_1', 'price_1', and so on.

One approach is to utilize the pivot method. Consider the following example with a fictional dataset:

<code class="python">import pandas as pd

data = {
    'Salesman': ['Knut', 'Knut', 'Knut', 'Steve'],
    'Height': [6, 6, 6, 5],
    'product': ['bat', 'ball', 'wand', 'pen'],
    'price': [5, 1, 3, 2]
}

df = pd.DataFrame(data)</code>
Copy after login

To reshape this long dataset into wide format, we can pivot on the 'Salesman' column and set the 'product' column as the new column headers while the 'price' column becomes the corresponding values:

<code class="python">df_wide = df.pivot(index='Salesman', columns='product', values='price')</code>
Copy after login

This will result in a wide format dataframe as desired:

<code class="python">print(df_wide)

   bat  ball  wand  pen
0   5    1    3   NaN
1   NaN  NaN  NaN    2</code>
Copy after login

This solution demonstrates how to reshape a long dataframe to a wide format using the pivot method, addressing the need for a straightforward method to perform such reshaping tasks in Pandas.

The above is the detailed content of How to Convert a Long Pandas DataFrame to Wide Format Using the Pivot Method?. 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