我目前正在研究各種未來曲線。每個截止日期都有一個可用的期貨曲線串列。我的最終目標是提取截至日期與每個人相關的到期日期值。下面是我的資料框的一個例子
asOfDate maturityDate value
0 2017-10-02 2017-10-01 406.8
1 2017-10-02 2017-11-01 406.8
2 2017-10-02 2017-12-01 398.3
3 2017-10-02 2018-01-01 398.3
4 2017-10-02 2018-02-01 390.2
5 2017-10-02 2018-03-01 390.2
6 2017-10-02 2018-04-01 380.5
7 2017-10-02 2018-05-01 380.5
8 2017-10-02 2018-06-01 385.0
9 2017-10-02 2018-07-01 385.0
10 2017-10-02 2018-08-01 385.0
11 2017-10-02 2018-09-01 385.0
12 2017-10-02 2018-10-01 383.2
13 2017-10-02 2018-11-01 383.2
14 2017-10-03 2017-10-01 410.4
15 2017-10-03 2017-11-01 410.4
16 2017-10-03 2017-12-01 400.8
17 2017-10-03 2018-01-01 400.8
18 2017-10-03 2018-02-01 392.5
19 2017-10-03 2018-03-01 392.5
最終目標將是每個到期日期相對于每個日期的最接近值的串列。因此,鑒于上述資料集,所需的輸出將是
asOfDate maturityDate value
0 2017-10-02 2017-10-01 406.8
14 2017-10-03 2017-10-01 410.4
鑒于合約在 2017-10-02 接近 asOfDate 是 2017-10-01 和 2017-10-03 最接近的是同一合約。
我的想法是我可以為每個日期做某種型別的 groupby,這是我迄今為止測驗過的
df_lumber[df_lumber['maturityDate']==df_lumber.groupby(['asOfDate'])['maturityDate'].apply(min)]
我正在嘗試匹配當前到期日以匹配每個截至日期的最小到期日,理論上這應該是我所追求的。
uj5u.com熱心網友回復:
OP 離期望的輸出不遠。
首先,確保兩列都datetime與pandas.to_datetime
df['asOfDate'] = pd.to_datetime(df['asOfDate'])
df['maturityDate'] = pd.to_datetime(df['maturityDate'])
然后,這將完成作業
df[df["maturityDate"] == df.groupby("asOfDate")["maturityDate"].transform(min)]
[Out]:
asOfDate maturityDate value
0 2017-10-02 2017-10-01 406.8
14 2017-10-03 2017-10-01 410.4
筆記:
一種是
asOfDate用分組pandas.DataFrame.groupby。并為每個組使用
.transform('min')來獲得該列的最小值maturityDate。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/512089.html
下一篇:熊貓同上年季度差異
