用途:
import pandas as pd
from io import StringIO
temp=u"""obs,yr30,tbill3m,ret3m
1990M01,7.98,7.8,0.028205
1990M02,8.44,8.02,0.007481
1990M03,8.61,8.08,-0.003713"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp),
index_col=0)
print (df)
yr30 tbill3m ret3m
obs
1990M01 7.98 7.80 0.028205
1990M02 8.44 8.02 0.007481
1990M03 8.61 8.08 -0.003713
然后通过to_datetime将索引转换为日期时间:
df.index = pd.to_datetime(df.index, format='%YM%m')
print (df)
yr30 tbill3m ret3m
obs
1990-01-01 7.98 7.80 0.028205
1990-02-01 8.44 8.02 0.007481
1990-03-01 8.61 8.08 -0.003713
然后到Series.dt.to_period的月份:
df.index = pd.to_datetime(df.index, format='%YM%m').to_period('m')
print (df)
yr30 tbill3m ret3m
obs
1990-01 7.98 7.80 0.028205
1990-02 8.44 8.02 0.007481
1990-03 8.61 8.08 -0.003713