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>
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>
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>
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!