CodexBloom - Programming Q&A Platform

How to retain original DataFrame index after pivoting with Pandas?

πŸ‘€ Views: 62 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-24
pandas dataframe pivot Python

I'm stuck trying to I'm working through a tutorial and I need help solving I just started working with I'm trying to pivot a DataFrame in Pandas, but after using the `pivot()` function, I notice that the original index is lost... My goal is to maintain the original index values in the resulting DataFrame after the pivoting operation. Here’s a minimal example of what I’m working with: ```python import pandas as pd data = { 'date': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02'], 'city': ['New York', 'Los Angeles', 'New York', 'Los Angeles'], 'temperature': [30, 75, 28, 70] } df = pd.DataFrame(data) # Setting 'date' as index # Original DataFrame looks like this: # city temperature # date # 2023-01-01 New York 30 # 2023-01-01 Los Angeles 75 # 2023-01-02 New York 28 # 2023-01-02 Los Angeles 70 # Pivoting the DataFrame pivot_df = df.pivot(index='date', columns='city', values='temperature') print(pivot_df) ``` After running this code, the `pivot_df` DataFrame looks like this: ```plaintext city Los Angeles New York date 2023-01-01 75 30 2023-01-02 70 28 ``` While I get the desired pivoted format, I've lost the original index of the DataFrame. I expected to keep the original index values with the pivoted data. I've tried resetting the index before pivoting with `df.reset_index()` but that changes the DataFrame structure in a way that doesn't meet my needs. Is there a way to achieve this while maintaining the original index after the pivoting process? Any help would be appreciated! I'm on Linux using the latest version of Python. Thanks for any help you can provide! Any examples would be super helpful. The project is a CLI tool built with Python. Thanks, I really appreciate it! The project is a REST API built with Python. Has anyone dealt with something similar?