【问题标题】:Find date in column, append adjacent column value to new column - all in one df?在列中查找日期,将相邻列值附加到新列 - 全部在一个 df 中?
【发布时间】:2021-04-26 21:48:54
【问题描述】:

我有一个包含 5 年股票指数价格的时间序列 df(所以 df 有 2 列日期和价格。然后我有一个新列“3M 远期日期”,它只是原始日期列 + 3 个月。

然后我尝试创建一个“3M 远期价格”列。这将是原始价格列中的对应价格,但在 3M 远期日期。

我需要找到说的语法: 从日期列中的 3M 远期日期列中查找日期,并将原始价格列中的相应值附加到新的 3M 远期价格列中。

我尝试了 .loc 想法的变体,并查看了几个历史问题,但鉴于我的查找值来自 df 列并且需要附加到新列,我无法弄清楚。

当前 DF 的一小部分:

  DATE       Price     Target Date 1  Price on Target Date 1
            
2019-01-22  3112.80     2019-04-22     <--need to lookup this date in DATE and return Price here
2019-01-23  3112.13     2019-04-23      
2019-01-24  3126.31     2019-04-24      
2019-01-25  3163.24     2019-04-25      

【问题讨论】:

    标签: pandas time-series append .loc


    【解决方案1】:

    所以如果列是 datepricetarget_date,我们要创建一个新列 target_price时间>。这个呢:

    date_price_dict = df.set_index("date").to_dict()["price"]
    df["target_date_price"] = df.apply(lambda x: date_price_dict.get(x["target_date"]), axis=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 2014-08-18
      • 1970-01-01
      相关资源
      最近更新 更多