简体   繁体   中英

Error when trying to change an index value in pandas dataframe (IndexError: too many indices for array)

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?

在此处输入图像描述

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'}) 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM