我正在練習圣路易斯聯儲的制造業資料集。在這里,我想了解一下,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:] 會導致錯誤訊息“無法使用這些索引器 [UMTMVS 2008-06-01 dtype: datetime64[ns]] 型別的 Series 對 DatetimeIndex 進行切片索引”
我在這里對stackoverflow進行了一些研究并嘗試使用
maxdate_str = maxdate.index.strftime('%Y-%m-%d')
afterpeak = df.loc[maxdate_str:]
但這也會產生錯誤('Index' 物件沒有屬性'strftime')。
有人可以幫我弄清楚這里的問題是什么嗎?
uj5u.com熱心網友回復:
為此,您需要提取該值,因為 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 年 6 月 1 日的最大值和切片 df.loc[maxdate[0]:] 時也會提取該值。因此,為了驗證,我們使用 iloc,您可以在其中隱式使用索引。在這個例子中,我們需要跳過第一個值,因為它是最大值。
print(afterpeak[afterpeak.iloc[1:] >= maxvalue[0]].dropna())
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491861.html
