【发布时间】:2022-06-11 00:13:04
【问题描述】:
我正在manufacturing data set by the St. Louis Fed 上练习。在这里,我想了解一下,2008年的高峰再次达到了多少个月。为此,我编写了以下代码:
# Set DATE as index and convert to datetime
df.set_index("DATE", inplace = True)
df.index = pd.to_datetime(df.index)
# Locate the date of the peak in 2008 and find out how high the peak was
maxdate = df.loc["2008-01-01":"2008-12-31"].idxmax()
maxvalue = df.loc[maxdate]["UMTMVS"]
#Create new data frame that encompasses the records after maxdate
afterpeak = df.loc[maxdate:]
# Create new data frame that encompasses all records in which the daily value was larger than the maxvalue of 2008
df2 = afterpeak[afterpeak>= maxvalue].dropna()
# Create new data frame that has the second instant in which the daily value was higher than maxvalue of 2008 (first value is maxdate itself)
samelevel = df[1]
# Count number of months between maxdate and second instant in which the daily value was higher than maxvalue of 2008
len(df2.loc[maxdate:samelevel])
虽然 maxdate 和 maxvalue 工作得很好,但我在下一行遇到了麻烦。我似乎无法将 maxdate 解析为 df.loc[maxdate:] 即使在 maxdate 中解析可以很好地生成最大值。但是,df.loc[maxdate:] 会导致错误消息“无法使用这些索引器对 DatetimeIndex 进行切片索引 [UMTMVS 2008-06-01 dtype: datetime64[ns]] 系列"
我在这里对 stackoverflow 进行了一些研究并尝试使用
maxdate_str = maxdate.index.strftime('%Y-%m-%d')
afterpeak = df.loc[maxdate_str:]
但这也会产生错误('Index' 对象没有属性 'strftime')。
谁能帮我弄清楚这里的问题是什么?
【问题讨论】:
-
从错误消息看来,您正在尝试在索引上应用
strftime而不是date值。 -
但是以日期为索引,我认为这将是这样做的方法。我在这里弄错了吗?
标签: python parsing datetimeindex