I'm trying to change an index value in my pandas dataframe with:
return1m.rename(index={'2022-08-30':'1 Month'})
but I keep getting an error:
IndexError: too many indices for array
And I don't see what I'm doing wrong. Could someone guide me?

CodePudding user response:
IIUC, You get an error because dtype of Date in the index is datetime so for renaming you need to pass datetime instead of a string.
from datetime import datetime
string_date_time = '2022-08-30'
_datetime = datetime.strptime(string_date_time, '%Y-%m-%d')
df.rename(index={_datetime:'1 Month'})
You can also convert datetime in index to string and then rename like that you do:
df.index = df.index.astype(str)
df.rename(index={'2022-08-30':'1 Month'})
CodePudding user response:
I'm guessing that the error is caused by the datetime object 2022-08-30 being deceivingly looking like a string '2022-08-30', but is actually datetime.datetime(2022, 8, 30, 0, 0).
You could simply rename the index using df.index.
df.index = ['1 Month']
print(df)
BTC-USD
1 Month -0.12
Getting OP's (truncated) dataframe:
import pandas as pd
df = pd.DataFrame({'Date': ['2022-08-30'], 'BTC-USD': [-0.12]})
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')
print(df)
BTC-USD
Date
2022-08-30 -0.12
