Logo

How to convert index of a pandas dataframe into a column?

If you want to make the existing index of a DataFrame into a regular column, the most common approach is to use reset_index(). By default, this method creates a new column for the current index and assigns the DataFrame a fresh range-based index:

import pandas as pd df = pd.DataFrame({ "A": [1, 2, 3], "B": [4, 5, 6] }, index=["row1", "row2", "row3"]) print("Original DataFrame:\n", df) df_reset = df.reset_index() print("\nDataFrame after resetting index:\n", df_reset)
  1. df.reset_index() returns a new DataFrame where the old index is now a regular column (named "index" if your index was unnamed).
  2. If you want the change to apply in place and not return a new DataFrame, you can do:
    df.reset_index(inplace=True)
  3. If your original index has a name, Pandas will use that name as the column heading. Otherwise, it defaults to "index".

Alternate Method: Manually Assign the Index to a New Column

You can also explicitly assign the index to a column:

df["old_index"] = df.index df.reset_index(drop=True, inplace=True)
  1. df["old_index"] = df.index creates a new column "old_index" using the current index.
  2. df.reset_index(drop=True) discards the original index, replacing it with a standard integer index (0, 1, 2, …).

This approach might be useful if you want a custom name for the new column or if you only want to store the index without discarding the existing one entirely.

Strengthen Your Python Fundamentals

To further hone your Python skills—particularly around data manipulation, best practices, and efficient coding—check out Grokking Python Fundamentals by DesignGurus.io. This course offers a clear, step-by-step approach to mastering Python 3, which can greatly streamline your data analysis and engineering tasks when working with libraries like Pandas.

By converting the index to a column appropriately, you’ll keep your DataFrame structure flexible for merging, filtering, or exporting to external formats where a purely numeric or labeled index may be less intuitive. Happy data wrangling!

CONTRIBUTOR
TechGrind