gpt4 book ai didi

python - 如何在 Pandas 中创建一列 ceil 日期

转载 作者:行者123 更新时间:2023-11-28 22:13:23 24 4
gpt4 key购买 nike

我想向 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: Can only use .dt accessor with datetimelike values

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

最佳答案

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

关于python - 如何在 Pandas 中创建一列 ceil 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54016264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com