Pandas数据框为:
year month count
0 2014 Jan 12
1 2014 Feb 10
2 2015 Jan 12
3 2015 Feb 10
如何从“年”和“月”创建DateTime索引,结果将是:
count
2014.01.31 12
2014.02.28 10
2015.01.31 12
2015.02.28 10
答案 0 :(得分:2)
将to_datetime
与DataFrame.pop
一起使用,并删除列并添加offsets.MonthEnd
:
dates = pd.to_datetime(df.pop('year').astype(str) + df.pop('month'), format='%Y%b')
df.index = dates + pd.offsets.MonthEnd()
print (df)
count
2014-01-31 12
2014-02-28 10
2015-01-31 12
2015-02-28 10
或者:
dates = pd.to_datetime(df.pop('year').astype(str) + df.pop('month'), format='%Y%b')
df.index = dates + pd.to_timedelta(dates.dt.daysinmonth - 1, unit='d')
print (df)
count
2014-01-31 12
2014-02-28 10
2015-01-31 12
2015-02-28 10