我正在由圣路易斯联邦储备银行设定的制造业数据上练习。在这里,我想知道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.locmaxdate:即使在maxdate中解析的效果非常好,也无法生成maxvalue。但是,df.locmaxdate:导致错误消息的结果“不能使用这些索引器在DatetimeIndex上执行切片索引[ummvs-2008-06-01dtype: datetime64ns]。”
我在这里研究了一些关于堆栈溢出的内容,并尝试使用
maxdate_str = maxdate.index.strftime('%Y-%m-%d')
afterpeak = df.loc[maxdate_str:]但是这也会产生一个错误('Index‘对象没有属性'strftime')。
有人能帮我弄清楚这是什么问题吗?
发布于 2022-06-10 16:13:04
要做到这一点,您需要提取值,因为maxdate是一个系列。
print(maxdate)输出
UMTMVS 2008-06-01得到价值:
print(maxdate[0])输出
2008-06-01 00:00:00获取所需的片段:
afterpeak = df.loc[maxdate[0]:]
print(afterpeak)请注意,loc包含了这个片段。也就是说,在本例中,2008-06-01年的最大值以及切片df.loc[maxdate:]时的值也将被提取。因此,为了进行验证,我们使用iloc,您可以在其中隐式使用索引。在这个例子中,我们需要跳过第一个值,因为它是maxvalue。
print(afterpeak[afterpeak.iloc[1:] >= maxvalue[0]].dropna())https://stackoverflow.com/questions/72570212
复制相似问题