Skip to main content
 首页 » 编程设计

python之想要每个月的最后一天作为 pandas 中的数据框

2025年05月04日14小虾米

我在 pandas 中有一个数据框,其中索引是工作日。我想只使用每个月的最后一天以及各个列中的相应数据来创建一个新的数据框。我尝试了几种不同的方法但收效甚微,我不断收到的错误消息是:AttributeError: 'DataFrame' object has no attribute 'date'。

我的数据框中的索引标记为“日期”。除了验证这一点,我不知道该去哪里。此外,此列中的日期包括小时、分钟和秒...不确定这是否重要。

下面是数据框的示例:

Date                   A    B    C 
11/27/2015 00:00:00    5    2    4 
11/30/2015 00:00:00    2    9    1 
12/1/2015  00:00:00    6    1    8 
12/2/2015  00:00:00    4    7    0 

我希望显示结果

11/30/2015 00:00:00    2  9  1 

我试过的一些代码如下:两者都有同样的错误。

prices = prices.resample('M', 'first') 
prices = prices.index + pd.offsets.MonthEnd(0) 

请您参考如下方法:

In [1]: df = pd.DataFrame({'a':range(1000)}, index=pd.date_range('2014-1-1', periods=1000)) 
 
In [2]: df.index.days_in_month 
Out[2]:  
array([31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 
       31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 28, 28, 28, 

如果日期在列中,而不是在索引中,您将执行 df['Date'].dt.days_in_month

编辑:

上面是如果你想要这个月的最后一天。相反,这听起来像你想要的? prices.index = prices.index + pd.offsets.MonthEnd(0)