2015-07-10 121 views
2

工作時,我有一個數據幀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每一行有多個付款或maturity_dtorig_iss_dt之間coupon的。這些情況每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) 
+0

它看起來像你想要原來的問題date'和'成熟度'所有優惠券日期「,與當前日期無關。所有這三個記錄都是30年期債券,那麼爲什麼不做''df.loc [0,'coupon']] * 60'來獲得完整的優惠券列表。 –

回答

0

有一個很大的問題與「應#creating列表中的」你在每次迭代的開始復位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)