我正在使用日期時間。反正有沒有得到 n 個月前的價值。
例如,資料如下所示:
dft = pd.DataFrame(
np.random.randn(100, 1),
columns=["A"],
index=pd.date_range("20130101", periods=100, freq="M"),
)
dft
然后:
- 對于每年的每個 7 月,我們取上一年 12 月的值并應用到明年 6 月
剩下的其他月份(從今年8月到明年6月),我們取上個月的值- 例如:從 2000 年 7 月到 2001 年 6 月的值將與 1999 年 12 月的值相同。
我一直在嘗試做的是:
dft['B'] = np.where(dft.index.month == 7,
dft['A'].shift(7, freq='M') ,
dft['A'].shift(1, freq='M'))
但是,結果只是 A 列的副本。我不知道為什么。但是當我嘗試單行代碼時:
dft['C'] = dft['A'].shift(7, freq='M')
然后一切都按預期轉移。我不知道這里有什么問題
uj5u.com熱心網友回復:
問題是索引對齊。您執行的這種轉變作用于索引,但使用numpy.where您轉換為陣列并丟失索引。
使用 pandas'where或者mask相反,所有內容都將保留為 Series 并且索引將被保留:
dft['B'] = (dft['A'].shift(1, freq='M')
.mask(dft.index.month == 7, dft['A'].shift(7, freq='M'))
)
輸出:
A B
2013-01-31 -2.202668 NaN
2013-02-28 0.878792 -2.202668
2013-03-31 -0.982540 0.878792
2013-04-30 0.119029 -0.982540
2013-05-31 -0.119644 0.119029
2013-06-30 -1.038124 -0.119644
2013-07-31 0.177794 -1.038124
2013-08-31 0.206593 -2.202668 <- correct
2013-09-30 0.188426 0.206593
2013-10-31 0.764086 0.188426
... ... ...
2020-12-31 1.382249 -1.413214
2021-01-31 -0.303696 1.382249
2021-02-28 -1.622287 -0.303696
2021-03-31 -0.763898 -1.622287
2021-04-30 0.420844 -0.763898
[100 rows x 2 columns]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472617.html
