import pandas as pd
import numpy as np
import osdf=pd.DataFrame(index=['a','b','c'],data={'序列':[1,2,3]})
df.rename(index={'a':'a1'},inplace=True)
print(df)
print(df.index.dtype)df1=pd.DataFrame(index=['2024-01-01','2024-01-02','2024-01-03'],data={'序列':[1,2,3]})
df1.rename(index={'2024-01-01':'a1'},inplace=True)
print(df1)
print(df1.index.dtype)df2=pd.DataFrame(index=pd.date_range('2024-01-01',periods=3,freq='D'),data={'序列':[1,2,3]})
# df2.rename(index={'2024-01-01':'2024-01-05'},inplace=True)
# 修改后的索引如果不是同类型,将会引起错误
print(df2.index.dtype)
df2.index=df2.index.astype('str')
df2.rename(index={'2024-01-01':'2024-01-05'},inplace=True)
print(df2)
运行结果:
案例:时间索引列在修改时,需要同类型之间修改,可以先把时间类型修改为字符类型,再修改,否则将会报错,报错提示如下:
File "lib.pyx", line 747, in pandas._libs.lib.ensure_string_array
File "lib.pyx", line 804, in pandas._libs.lib.ensure_string_array
IndexError: too many indices for array