gpt4 book ai didi

python - 创建每月的 pandas DatetimeIndex

转载 作者:行者123 更新时间:2023-12-01 04:00:49 26 4
gpt4 key购买 nike

我有一个包含 12 个值的数据框,我想将其转换为 DatetimeIndex 类型

months = df['date'] #e.g. '2016-04-01'
idx = pd.date_range(months[0], months[11], freq='M')

但是,生成的DatetimeIndex长度只有11,应该是12不确定是否是因为频率的原因,将日期移至月末?

最佳答案

对我来说,工作是用句点生成的:

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.

关于python - 创建每月的 pandas DatetimeIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36591783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com