【问题标题】:Problems parsing in datetime index日期时间索引中的解析问题
【发布时间】: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


【解决方案1】:

为此,您需要提取值,因为 maxdate 是一个系列。

print(maxdate)

输出

UMTMVS   2008-06-01

获取值:

print(maxdate[0])

输出

 2008-06-01 00:00:00

得到想要的片段:

afterpeak = df.loc[maxdate[0]:]
print(afterpeak)

输出

              UMTMVS
DATE                
2008-06-01  510081.0
2008-07-01  476948.0
2008-08-01  482530.0
2008-09-01  471799.0
2008-10-01  450521.0
...              ...
2021-12-01  507124.0
2022-01-01  472569.0
2022-02-01  482953.0
2022-03-01  568556.0
2022-04-01  530355.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2012-11-06
    • 2021-06-19
    • 1970-01-01
    • 2017-04-16
    • 2022-01-16
    • 2013-10-17
    相关资源
    最近更新 更多