CodexBloom - Programming Q&A Platform

How to Preserve DataFrame Index While Pivoting in Pandas?

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
pandas dataframe pivot Python

I'm trying to pivot a DataFrame in Pandas, but I want to preserve the original index in the resulting DataFrame. I'm using Pandas version 1.3.3 and my DataFrame looks like this: ```python import pandas as pd df = pd.DataFrame({ 'date': ['2021-01-01', '2021-01-01', '2021-01-02', '2021-01-02'], 'category': ['A', 'B', 'A', 'B'], 'value': [10, 20, 30, 40] }) df.set_index('date', inplace=True) ``` When I pivot the DataFrame using the `pivot` method, it resets the index: ```python pivoted = df.pivot(index='date', columns='category', values='value') print(pivoted) ``` This results in a DataFrame that no longer has the original date index, which is not what I want. The output is: ``` category A B date 2021-01-01 10.0 20.0 2021-01-02 30.0 40.0 ``` I tried using `set_index` again after the pivot, but that feels redundant. Is there a more efficient way to retain the index during the pivoting process? I've also looked into `pivot_table`, but it seems like it behaves similarly. Any advice on how to achieve this without losing the original index would be greatly appreciated!