pandas 熊猫生成开始月份的日期范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21420165/
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-09-13 21:38:25  来源:igfitidea点击:

Pandas generate date range of Beginning Month

pythonpandas

提问by dartdog

What is going on here? I need to generate a dataframe with beginning of month dates,,(1-1-2014 To 12-1-2014) fwiw I use the fcast_year variable elsewhere where I need the end of month, hence doing date math

这里发生了什么?我需要生成一个带有月初日期的数据框,(1-1-2014 到 12-1-2014) fwiw 我在其他需要月底的地方使用 fcast_year 变量,因此做日期数学

from pandas.tseries.offsets import *
fcast_yr=pd.to_datetime('2014-12-31')
x=(fcast_yr + pd.DateOffset(days= -30)) # to set x to 2014-12-01
d=pd.date_range((x +pd.DateOffset(months=-10)), periods=12, freq='MS') #"MS" means start of month!!
print d.values

Gives these end of month values....yech!!

给出这些月末值....耶!

['2014-01-31T18:00:00.000000000-0600' '2014-02-28T18:00:00.000000000-0600'
 '2014-03-31T19:00:00.000000000-0500' '2014-04-30T19:00:00.000000000-0500'
 '2014-05-31T19:00:00.000000000-0500' '2014-06-30T19:00:00.000000000-0500'
 '2014-07-31T19:00:00.000000000-0500' '2014-08-31T19:00:00.000000000-0500'
 '2014-09-30T19:00:00.000000000-0500' '2014-10-31T19:00:00.000000000-0500'
 '2014-11-30T18:00:00.000000000-0600' '2014-12-31T18:00:00.000000000-0600']

Using 13.0 pf Pandas

使用 13.0 pf Pandas

回答by Jeff

You don't need to coerce the timestamp to the begin month; the frequency will do it (but your answer is correct).

您不需要将时间戳强制为开始月份;频率会做到这一点(但你的答案是正确的)。

The 'values' are just the way numpy represents dates (they are UTC).

“值”只是 numpy 表示日期的方式(它们是 UTC)。

In [8]: pd.date_range((Timestamp('20141231') +pd.DateOffset(months=-11)), periods=12, freq='MS')
Out[8]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-02-01, ..., 2015-01-01]
Length: 12, Freq: MS, Timezone: None