查找 Pandas DataFrame 系列的月底 [英] Find the end of the month of a Pandas DataFrame Series

查看:46
本文介绍了查找 Pandas DataFrame 系列的月底的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 DataFrame 中有一个系列,我最初将其作为对象读入,然后需要将其转换为 yyyy-mm-dd 形式的日期,其中 dd 是月末​​.

I have a series within a DataFrame that I read in initially as an object, and then need to convert it to a date in the form of yyyy-mm-dd where dd is the end of the month.

举个例子,我有一个 DataFrame df,有一列 Date 作为对象:

As an example, I have DataFrame df with a column Date as an object:

...      Date    ...
...     200104   ...
...     200508   ...

当这一切都说完后,我想要的是一个日期对象:

What I want when this is all said and done is a date object:

...      Date    ...
...  2001-04-30  ...
...  2005-08-31  ...

这样 df['Date'].item() 返回

such that df['Date'].item() returns

datetime.date(2001, 04, 30)

我已经使用以下代码几乎完成了,但我所有的日期都在月初,而不是月底.请指教.

I've used the following code to get almost there, but all my dates are at the beginning of the month, not the end. Please advise.

df['Date'] = pd.to_datetime(df['Date'], format="%Y%m").dt.date

注意:我已经将 Pandas ad pd 和 datetime 导入为 dt

Note: I've already imported Pandas ad pd, and datetime as dt

推荐答案

您可以使用 pandas.tseries.offsets.MonthEnd:

You can use pandas.tseries.offsets.MonthEnd:

from pandas.tseries.offsets import MonthEnd

df['Date'] = pd.to_datetime(df['Date'], format="%Y%m") + MonthEnd(1)

MonthEnd 中的 1 只是指定向前移动一步到下一个月底的日期.(使用 0 或将其留空也适用于您的情况).如果你想要下个月的最后一天,你可以使用 MonthEnd(2) 等.这应该适用于任何一个月,所以你不需要知道当月的天数,或类似的东西.更多偏移信息可以在文档.

The 1 in MonthEnd just specifies to move one step forward to the next date that's a month end. (Using 0 or leaving it blank would also work in your case). If you wanted the last day of the next month, you'd use MonthEnd(2), etc. This should work for any month, so you don't need to know the number days in the month, or anything like that. More offset information can be found in the documentation.

示例用法和输出:

df = pd.DataFrame({'Date': [200104, 200508, 201002, 201602, 199912, 200611]})
df['EndOfMonth'] = pd.to_datetime(df['Date'], format="%Y%m") + MonthEnd(1)

     Date EndOfMonth
0  200104 2001-04-30
1  200508 2005-08-31
2  201002 2010-02-28
3  201602 2016-02-29
4  199912 1999-12-31
5  200611 2006-11-30

这篇关于查找 Pandas DataFrame 系列的月底的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆