Rename Pandas DataFrame Index

ghz 3months ago ⋅ 101 views

I've a csv file without header, with a DateTime index. I want to rename the index and column name, but with df.rename() only the column name is renamed. Bug? I'm on version 0.12.0

In [2]: df = pd.read_csv(r'D:\Data\DataTimeSeries_csv//seriesSM.csv', header=None, parse_dates=[[0]], index_col=[0] )

In [3]: df.head()
Out[3]: 
                   1
0                   
2002-06-18  0.112000
2002-06-22  0.190333
2002-06-26  0.134000
2002-06-30  0.093000
2002-07-04  0.098667

In [4]: df.rename(index={0:'Date'}, columns={1:'SM'}, inplace=True)

In [5]: df.head()
Out[5]: 
                  SM
0                   
2002-06-18  0.112000
2002-06-22  0.190333
2002-06-26  0.134000
2002-06-30  0.093000
2002-07-04  0.098667

Answers

The issue you're encountering is not a bug but rather a misunderstanding of how the rename() method works for the index when using inplace=True.

The index parameter in rename() is used to rename specific values of the index, not to change the index name itself. What you actually want to do is rename the index label (i.e., the name of the index). To do that, you should assign a name to the index using .index.name.

Here’s how you can rename both the index and the column properly:

import pandas as pd

# Assuming you've already read the CSV
df = pd.read_csv(r'D:\Data\DataTimeSeries_csv\seriesSM.csv', header=None, parse_dates=[[0]], index_col=[0])

# Rename the column using rename()
df.rename(columns={1: 'SM'}, inplace=True)

# Rename the index using .index.name
df.index.name = 'Date'

# Display the dataframe
print(df.head())

Output:

                     SM
Date                  
2002-06-18  0.112000
2002-06-22  0.190333
2002-06-26  0.134000
2002-06-30  0.093000
2002-07-04  0.098667

Explanation:

  • df.rename(columns={1: 'SM'}, inplace=True): This renames column 1 to SM.
  • df.index.name = 'Date': This assigns the name 'Date' to the index, which is what you're trying to achieve.

This will correctly rename both the index label and the column name in your DataFrame.