所以我試圖將我的資料更改為每月的頻率以獲得更好的情節。我的代碼是:
ice_cream_interest = pd.read_excel('book1.xlsx')
ice_cream_interest.set_index('Month', inplace= True)
ice_cream_interest = ice_cream_interest.asfreq(pd.infer_freq(ice_cream_interest.index))
ice_cream_interest 本身的資料是這樣的:
Month interest
0 2004-01 20
1 2004-02 21
2 2004-03 22
3 2004-04 25
4 2004-05 29
但是在我運行我的代碼之后,它給出了:
interest
Month
2004-01-01 NaN
2004-02-01 NaN
2004-03-01 NaN
2004-04-01 NaN
2004-05-01 NaN
所以我想知道為什么 asfreq 會回傳一個 NaN,以及如何解決它。謝謝!
uj5u.com熱心網友回復:
該asfreq檔案指定:
除非提供了填充此類未知數的方法(請參閱下面的方法引數),否則與新索引中不存在于原始索引中的任何時間步對應的值將為空 (NaN)。
當您從月份更改為每月的第一天時,您會更改索引并丟失所有資料。
如果您需要重新采樣,請使用該resample方法。
但是,在這里您可以將月份轉換為日期:
ice_cream_interest = (ice_cream_interest
.assign(Date=lambda d: pd.to_datetime(d['Month']))
.set_index('Date')
.drop(columns='Month')
)
輸出:
interest
Date
2004-01-01 20
2004-02-01 21
2004-03-01 22
2004-04-01 25
2004-05-01 29
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466422.html
標籤:Python python-3.x 熊猫 数据框 楠
