跨2个数据帧应用函数

2024-05-10 03:48:00 发布

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

我有两个数据帧使用excel。目前,我正面临着一个挑战,试图在2个数据帧中应用一个基于列标题和列值的函数。你知道吗

Dataframe A(bondDf)是绑定数据,其中第一列是索引(也尝试使用多索引头,但失败)

ISIN    ABCDE123    DEFGHI245   ASKDNA123   AJSNDJAKS2
Issue Date  18/01/2005  31/01/2008  15/02/2000  15/02/2007
Maturity    15/01/2010  31/01/2010  15/02/2010  15/02/2010
First Coupon Date   15/07/2005  31/07/2008  15/08/2000  15/08/2007
Cpn 3.9875  2.3375  7.15    5.225
31/12/2008  103.515625  101.875 106.609375  104.796875
30/01/2009  102.9375    101.546875  106.109375  104.28125
27/02/2009  102.546875  101.234375  105.453125  103.796875
31/03/2009  102.453125  101.296875  105.140625  103.609375
30/04/2009  102.3125    101.28125   104.796875  103.40625

enter image description here

数据帧B(futuresDf)是未来数据,其中第一列同样被索引

Index   FUT_DLV_DT_FIRST
31/12/2008  02/03/2009
30/01/2009  02/03/2009
27/02/2009  02/03/2009
31/03/2009  01/06/2009
30/04/2009  01/06/2009

enter image description here

我正在尝试为bonddf中的每个债券价格应用下面的函数(103.51、101.875等)

def inBasket(b_issueDate, b_maturityDate, f_firstDeliveryDate, currentDate):
if b_issueDate < currentDate:

    DateDiffMonths          =   (f_firstDeliveryDate - b_maturityDate).days
    # other simple computation below

到目前为止,我尝试的是:

bondDf.iloc[6:].apply(lambda x: inBasket(f_contract, x.loc['Issue Date'], 
                x.loc['Maturity'], futuresDf.iloc[:]['FUT_DLV_DT_FIRST'], 
                bondDf.index.values[6:]), 0))

非常感谢您的帮助!你知道吗


Tags: 数据函数datedtissuefirstfutmaturity
1条回答
网友
1楼 · 发布于 2024-05-10 03:48:00

我不知道如何链接这两个帧(显然,按日期,但输出示例可以清除这一点),但我猜如果要使用日期作为输入,则必须使用futuresDf作为输入。我的猜测是对BondDf使用布尔索引,比如

 bondDf[bondDf.index==futuresDf] and perform the assignation from there. Or use a where method.

但是我认为你选择了一种不好的方式来表示你的框架中的数据,因为它们不适合自然。如果在数据帧中明确了关系,就可以很容易地连接/操作它们。在这里做不到。我甚至无法预测未来预测行的标题是什么,这些行对应于要与bondsDf第二列比较的五个日期。
如果我手头有这样一个问题,我会将数据重构为每个原始bondsDf列的一个帧,使五行与每个futuresDf行匹配,或者转置原始dataframes并连接它们。这样比较会更容易。你知道吗

编辑: 我将采取以下措施:采取你的df债券和计算,如果每个日期的指数(作为“当前日期”)将低于“发行日期”):

df
Out[53]: 
                            1           2           3           4
0                                                                
ISIN                 ABCDE123   DEFGHI245   ASKDNA123  AJSNDJAKS2
Issue Date         18/01/2005  31/01/2008  15/02/2000  15/02/2007
Maturity           15/01/2010  31/01/2010  15/02/2010  15/02/2010
First Coupon Date  15/07/2005  31/07/2008  15/08/2000  15/08/2007
Cpn                    3.9875      2.3375        7.15       5.225
31/12/2008         103.515625     101.875  106.609375  104.796875
30/01/2009           102.9375  101.546875  106.109375   104.28125
27/02/2009         102.546875  101.234375  105.453125  103.796875
31/03/2009         102.453125  101.296875  105.140625  103.609375
30/04/2009           102.3125   101.28125  104.796875   103.40625

sd=df.loc("Issue Date",:)
truth =sd.apply(lambda x: x<df.index[5:])

从这里开始,您使用基于相同原理的所有df的其他日期执行计算,然后根据真值分配基数,然后通过正确的方式切片并使用两个数据帧按元素执行操作来处理相应的值。例如测向位置[5:,:]*值基于真值*标量。。。你知道吗

相关问题 更多 >