【问题标题】:Setting up an empty time series dataframe with monthly data for the FIRST day of the month设置一个空的时间序列数据框,其中包含每月第一天的每月数据
【发布时间】:2015-05-20 06:24:15
【问题描述】:

当我使用

设置一个空的 pandas 数据框时
GWdates = pd.date_range('1/1/1940',periods = 900, freq='M')
Big_df= pd.DataFrame(index=GWdates)

我明白了:

In [265]: df5
Out[265]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 900 entries, 1940-01-31 00:00:00 to 2014-12-31 00:00:00
Freq: M
Empty DataFrame

日期都是月末,如何让它成为本月的第一天,

DatetimeIndex: 900 entries, 1940-01-01 00:00:00 to 2014-12-01 00:00:00

似乎MonthBegin 将是我正在搜索的内容,但我没有得到docs for it。似乎我必须在后台覆盖某些东西,我宁愿不这样做。

【问题讨论】:

    标签: python datetime pandas time-series


    【解决方案1】:

    你可以使用offsets.MonthBegin():

    In [280]: import pandas.tseries.offsets as offsets
    
    In [281]: pd.date_range('1/1/1940', periods=900, freq=offsets.MonthBegin())
    Out[281]: 
    <class 'pandas.tseries.index.DatetimeIndex'>
    [1940-01-01, ..., 2014-12-01]
    Length: 900, Freq: MS, Timezone: None
    

    或者,实际上,正如上面的 Freq: MS 所示,只需 freq='MS' 即可:

    In [282]: pd.date_range('1/1/1940', periods=900, freq='MS')
    Out[282]: 
    <class 'pandas.tseries.index.DatetimeIndex'>
    [1940-01-01, ..., 2014-12-01]
    Length: 900, Freq: MS, Timezone: None
    

    【讨论】:

    • freq='MS' 似乎正是我想要的!谢谢。我知道这可能真的很琐碎,但我自己找不到。
    猜你喜欢
    • 2021-09-24
    • 2020-10-02
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2021-06-11
    • 1970-01-01
    相关资源
    最近更新 更多