创建每月 pandas DatetimeIndex
Create monthly pandas DatetimeIndex
我有一个包含 12 个值的数据框,我想将其转换为 DatetimeIndex 类型
months = df['date'] #e.g. '2016-04-01'
idx = pd.date_range(months[0], months[11], freq='M')
但是得到的DatetimeIndex长度只有11,应该是12
不确定是不是因为频率的原因,它会将日期移到月底?
我用 periods
生成:
print df
date
0 2016-01-01
1 2016-02-01
2 2016-03-01
3 2016-04-02
print pd.date_range(df['date'].iloc[0], periods=12, freq='M')
DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31', '2016-04-30',
'2016-05-31', '2016-06-30', '2016-07-31', '2016-08-31',
'2016-09-30', '2016-10-31', '2016-11-30', '2016-12-31'],
dtype='datetime64[ns]', freq='M')
为什么缺少最后一个值 - check in the end:
months = df['date']
print pd.date_range(months.iloc[0], months.iloc[3], freq='M')
DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31'], dtype='datetime64[ns]', freq='M')
The start and end dates are strictly inclusive. So it will not generate any dates outside of those dates if specified.
我有一个包含 12 个值的数据框,我想将其转换为 DatetimeIndex 类型
months = df['date'] #e.g. '2016-04-01'
idx = pd.date_range(months[0], months[11], freq='M')
但是得到的DatetimeIndex长度只有11,应该是12 不确定是不是因为频率的原因,它会将日期移到月底?
我用 periods
生成:
print df
date
0 2016-01-01
1 2016-02-01
2 2016-03-01
3 2016-04-02
print pd.date_range(df['date'].iloc[0], periods=12, freq='M')
DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31', '2016-04-30',
'2016-05-31', '2016-06-30', '2016-07-31', '2016-08-31',
'2016-09-30', '2016-10-31', '2016-11-30', '2016-12-31'],
dtype='datetime64[ns]', freq='M')
为什么缺少最后一个值 - check in the end:
months = df['date']
print pd.date_range(months.iloc[0], months.iloc[3], freq='M')
DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31'], dtype='datetime64[ns]', freq='M')
The start and end dates are strictly inclusive. So it will not generate any dates outside of those dates if specified.