如何在 pandas 中创建列日期 [英] How to create a column of ceil dates in pandas

查看:89
本文介绍了如何在 pandas 中创建列日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向熊猫数据框添加一个月末日期的列。根据此答案,我尝试了以下操作:

I want to add a column that is the end-of-the-month date to a pandas dataframe. Based on this answer, I tried the following:

import numpy as np
import pandas as pd

dates = ['2014-06-02', '2014-06-03', '2014-06-04', '2014-06-05', '2014-06-06']
sp500_index = [1924.969971, 1924.23999, 1927.880005, 1940.459961, 1949.439941]
df_sp500 = pd.DataFrame({'Date' : dates, 'Close' : sp500_index})
sp500['Date'] = pd.to_datetime(sp500['Date'], format='%Y-%m-%d')
df_sp500['EOM'] = df_sp500['Date'].dt.ceil('M')  # breaks on this line
#df_sp500 = df_sp500[df_sp500['Date'] == df_sp500['EOM']]

df_sp500

但我收到此错误消息:


AttributeError:只能将.dt访问器与datetimelike值一起使用

AttributeError: Can only use .dt accessor with datetimelike values

我想添加此列的原因是使用它来过滤除EOM日期以外的所有日期,如图所示。

The reason I want to add this column is to use it to filter out all but the EOM dates as shown in the commented out line.

推荐答案

这已经内置于 datetime pandas。 Series.is_month_end

This is already built-in to datetime with pandas.Series.is_month_end. Instead of calculating a new column just subset with:

df_sp500[df_sp500.Date.dt.is_month_end]



输入数据



Input Data

dates = ['2014-06-02', '2014-06-03', '2014-06-04', '2014-06-05', '2014-06-06']
sp500_index = [1924.969971, 1924.23999, 1927.880005, 1940.459961, 1949.439941]

df_sp500 = pd.DataFrame({'Date' : dates, 'Close' : sp500_index})
df_sp500['Date'] = pd.to_datetime(df_sp500['Date'], format='%Y-%m-%d')

这篇关于如何在 pandas 中创建列日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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