【问题标题】:How to create a column of ceil dates in pandas如何在熊猫中创建一列 ceil 日期
【发布时间】:2019-01-03 04:14:26
【问题描述】:

我想在 pandas 数据框中添加一个表示月末日期的列。基于这个answer,我尝试了以下方法:

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: 只能使用带有 datetimelike 值的 .dt 访问器

我想添加此列的原因是使用它来过滤除 EOM 日期之外的所有日期,如注释掉的行中所示。

【问题讨论】:

  • 你有df_sp500 =sp500['Date'] =。是哪个?
  • 对 pandas 非常陌生(来自 R)。意图是 df_sp500 = 创建数据框和 sp500['Date'] = 行将 Date 字段从字符串转换为日期时间。

标签: python python-3.x pandas dataframe


【解决方案1】:
import numpy as np
import pandas as pd
from pandas.tseries.offsets import MonthEnd


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['EOM'] = pd.to_datetime(df_sp500['Date'], format='%Y-%m-%d')+ MonthEnd(0)
#df_sp500['EOM']=df_sp500['EOM'].dt.day #add this if you want only day

【讨论】:

  • @ALollz 的答案正是我想要的,但感谢您的出色回答。
【解决方案2】:

这已经内置到datetimepandas.Series.is_month_end。而不是计算一个新列只是子集:

df_sp500[df_sp500.Date.dt.is_month_end]

输入数据

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')

【讨论】:

  • 正是我想要的。谢谢。
【解决方案3】:

根据文档

索引上限的频率级别。必须是固定频率 像“S”(秒)而不是“ME”(月末)

所以我们可以为您的情况使用MonthBegin

df_sp500['Date']- pd.offsets.MonthBegin(1) #pd.offsets.MonthEnd(1)
0   2014-06-01
1   2014-06-01
2   2014-06-01
3   2014-06-01
4   2014-06-01
Name: Date, dtype: datetime64[ns]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2018-07-13
    • 2021-02-12
    • 2020-12-23
    • 2023-03-08
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多