使用日期时的空列表

时间:2015-07-10 03:11:18

标签: python pandas

我的数据框df如下所示:

       index  months_to_maturity          asset_id            orig_iss_dt  \
0   529300                   6     (BINARY DATA)  1985-11-29 00:00:00.0   
1   530920                  12     (BINARY DATA)  1986-05-13 00:00:00.0   
2   529302                  18     (BINARY DATA)  1986-11-17 00:00:00.0  

       maturity_dt         pay_freq_cd  coupon  closing_price  FACE_VALUE  
0   2015-11-15 00:00:00.0            2   9.875     103.390625         100   
1   2016-05-15 00:00:00.0            2   7.950     106.017000         100   
2   2016-11-15 00:00:00.0            2   7.500     109.515625         100   

对于df的每一行,couponmaturity_dt之间有多次付款或orig_iss_dt。这些事情每6个月发生一次,我试图将它们列入list_of_coupons列表中。这两个日期之间每6个月,我想要一张优惠券。但是,我目前得到一个空列表。

#Gets the difference in months between two datetimes
def monthdelta(d1, d2):
    delta = 0
    while True:
        mdays = monthrange(d1.year, d1.month)[1]
        d1 += timedelta(days=mdays)
        if d1 <= d2:
            delta += 1
        else:
            break
    return delta

#Creating the list
for (i,row) in df.iterrows():
     list_of_coupons = []
     for k in range(monthdelta(datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f'), datetime.datetime.strptime(row['orig_iss_dt'], '%Y-%m-%d %H:%M:%S.%f')), 0, -6):
         list_of_coupons.append(row.coupon)

1 个答案:

答案 0 :(得分:0)

“#Creating the list”中存在一个大问题,即您在每次迭代开始时将list_of_coupons重置为空列表。所以在你追加一个项目后,你就会删除它

尝试将其移至循环外部,如下所示:

#Creating the list
list_of_coupons = []
for (i,row) in df.iterrows():
for k in range(monthdelta(datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f'), datetime.datetime.strptime(row['orig_iss_dt'], '%Y-%m-%d %H:%M:%S.%f')), 0, -6):
         list_of_coupons.append(row.coupon)