想要每个月的最后一天获取

想要每个月的最后一天获取

本文介绍了想要每个月的最后一天获取 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在熊猫那里有一个数据框,其中索引是工作日.我只想使用每个月的最后一天以及各个列中的相应数据来创建一个新的数据框.我尝试了几种不同的方法,但收效甚微,并且不断出现的错误消息是:AttributeError:"DataFrame"对象没有属性"date".

I have a data frame in pandas where the index are business days. I want to create a new data frame using only the last day of each month, along with the corresponding data in the various columns. I have tried a few different ways with little success and the error message I keep getting is: AttributeError: 'DataFrame' object has no attribute 'date'.

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

The index in my data frame is labeled 'Date'. Other than verifying that, I don't know where to go. Also, the dates in this column include hours, minutes, and seconds...not sure if that matters.

下面是数据框的示例:

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

我尝试过的一些代码如下:两者都出现相同的错误.

Some of the code I have tried is as follows: Got the same error with both.

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

If instead the dates are in a column, not the index, you would do df['Date'].dt.days_in_month

以上是您是否希望自己一个月的最后一天.相反,这听起来像您想要的吗? prices.index = prices.index + pd.offsets.MonthEnd(0)

Above is if you had wanted the last day of the month by itself. Instead, it sounds like you want? prices.index = prices.index + pd.offsets.MonthEnd(0)

这篇关于想要每个月的最后一天获取 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:16