Python Pandas date_range 在月初生成月度数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34915828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:43:15  来源:igfitidea点击:

Pandas date_range to generate monthly data at beginning of the month

pythonpandasdate-range

提问by Bunny_Ross

I'm trying to generate a date range of monthly data where the day is always at the beginning of the month:

我正在尝试生成每月数据的日期范围,其中这一天总是在月初:

pd.date_range(start='1/1/1980', end='11/1/1991', freq='M')

This generates 1/31/1980, 2/29/1980, and so on. Instead, I just want 1/1/1980, 2/1/1980,...

这会生成1/31/19802/29/1980等等。相反,我只想要1/1/1980, 2/1/1980,...

I've seen other question ask about generating data that is always on a specific day of the month, with answers saying it wasn't possible, but beginning of month surely must be possible!

我已经看到其他问题询问有关生成始终在一个月中的特定日期生成数据的问题,答案说这是不可能的,但是月初肯定是可能的!

采纳答案by Dimitris Fasarakis Hilliard

You can do this by changing the freqargument from 'M'to 'MS':

您可以通过改变这样做freq从论证'M''MS'

d = pandas.date_range(start='1/1/1980', end='11/1/1990', freq='MS')    
print(d)

This should now print:

现在应该打印:

DatetimeIndex(['1980-01-01', '1980-02-01', '1980-03-01', '1980-04-01',
               '1980-05-01', '1980-06-01', '1980-07-01', '1980-08-01',
               '1980-09-01', '1980-10-01', 
               ...
               '1990-02-01', '1990-03-01', '1990-04-01', '1990-05-01',
               '1990-06-01', '1990-07-01', '1990-08-01', '1990-09-01',
               '1990-10-01', '1990-11-01'],
              dtype='datetime64[ns]', length=131, freq='MS', tz=None)

Look into the offset aliasespart of the documentation. There it states that 'M'is for the end of the month (month end frequency) while 'MS'for the beginning (month start frequency).

查看文档的偏移别名部分。那里说明'M'是月末(月末频率)'MS'和月初(月开始频率)。