In this tutoriual, we will learn how to convert the row name or row index name in a Pandas dataframe to a column. We will use Pandas’ reset_index() function to convert the index with name to a column.
Let us load Pandas.
import pandas as pd
pd.<strong>version</strong> '2.1.4'
Let us create a small dataframe in Pandas with rown index names.
stock_price = [426, 422, 418,417, 408] symbol = ["MSFT","MSFT","MSFT","MSFT","MSFT"] date = ['2024-07-29', '2024-07-30', '2024-07-31', '2024-08-01', '2024-08-02']
Our toy data frame has date values as row index names.
df = pd.DataFrame({'symbol':symbol, 'price': stock_price}, index=date) df <pre><code>symbol price </code></pre> 2024-07-29 MSFT 426 2024-07-30 MSFT 422 2024-07-31 MSFT 418 2024-08-01 MSFT 417 2024-08-02 MSFT 408
And the date is a a key variable of the dataframe and it is better be one of the columns instead of row index names. To conver the row index name we will use two steps.
In the first step, we will specify a name to the row index name.
df.index.name = "date"
We can see that now the dataframe looks like this with the name for the row index.
symbol price date<br /> 2024-07-29 MSFT 426 2024-07-30 MSFT 422 2024-07-31 MSFT 418 2024-08-01 MSFT 417 2024-08-02 MSFT 408
It is multi-index dataframe, we can simply it with Pandas reset_index() function.
df.reset_index() date symbol price 0 2024-07-29 MSFT 426 1 2024-07-30 MSFT 422 2 2024-07-31 MSFT 418 3 2024-08-01 MSFT 417 4 2024-08-02 MSFT 408
Another way to convert row index as a separate column in the dataframe us to use Pandas’ rename_axis() function with Pandas reset_index() function. An advantage of this approach is that we can chain these two functions into a single statement as shown below.
(df .rename_axis("Date") .reset_index() )
And we get the result we need.
Date symbol price 0 2024-07-29 MSFT 426 1 2024-07-30 MSFT 422 2 2024-07-31 MSFT 418 3 2024-08-01 MSFT 417 4 2024-08-02 MSFT 408