柱间条件下的最优行选择

2024-09-28 05:21:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

            dataPoint   RIC ExpirationDate          Exchange Description  \
closingDate                                                                
2002-10-15       4207  SPH3     2003-03-20  CME:Index and Options Market   
2002-10-15       5400  SPH4     2004-03-18  CME:Index and Options Market   
2002-10-15      18661  SPM3     2003-06-19  CME:Index and Options Market   
2002-10-15      19918  SPM4     2004-06-17  CME:Index and Options Market   
2002-10-15      33439  SPU3     2003-09-18  CME:Index and Options Market   
2002-10-15      35523  SPU4     2004-09-16  CME:Index and Options Market   
2002-10-15      47733  SPZ2     2002-12-19  CME:Index and Options Market   
2002-10-15      49022  SPZ3     2003-12-18  CME:Index and Options Market 

我想获取ExpirationDate最接近closingDate的行(注意,静态closingDate存储在名为current_date的变量中)

iterrows()是我想到的一种解决方案,但它似乎效率低下。有没有一种最佳的方法来进行这种条件选择


Tags: and数据indexexchangedescriptionmarketoptionscme
1条回答
网友
1楼 · 发布于 2024-09-28 05:21:50

找到最小绝对差的索引和索引

v = pd.to_datetime(df.reset_index()['ExpirationDate'])
idx = (v.mask(v < current_date) 
           - pd.to_datetime(current_date)).abs().idxmin()
row = df.iloc[idx, :]

我在这里看到一个问题:如果索引值不是唯一的,那么您将需要在位置上索引,而不是标签。因此,我添加了reset_index调用

相关问题 更多 >

    热门问题