【问题标题】:Repeat Values in Pandas between certain dates在特定日期之间重复 Pandas 中的值
【发布时间】:2018-01-09 21:31:55
【问题描述】:

我有两个数据框 A 和 B,其中 A 具有连续数据值,B 具有每周一次的值。如何合并两个数据帧,以使 B 数据帧中的值重复,直到它到达 A 数据帧中的一周结束。

示例: 'A' 数据框看起来像这样

Date        Price
2018-01-03  61.63
2018-01-01  60.42
2017-12-29  60.42
2017-12-28  59.84
2017-12-27  59.64
2017-12-26  59.97
2017-12-22  58.47
2017-12-21  58.36
2017-12-20  58.09
2017-12-19  57.97
2017-12-18  57.92
2017-12-17  57.79

'B' Dataframe 看起来像这样

Week        Week Price
2017-12-29  9782 
2017-12-22  9754
2017-12-15  9789

我期待这样的输出:

Date        Price  Week Price
2018-01-03  61.63  9782
2018-01-01  60.42  9782
2017-12-29  60.42  9782
2017-12-28  59.84  9754
2017-12-27  59.64  9754
2017-12-26  59.97  9754
2017-12-22  58.47  9754
2017-12-21  58.36  9789
2017-12-20  58.09  9789
2017-12-19  57.97  9789
2017-12-18  57.92  9789
2017-12-17  57.79  9789

【问题讨论】:

    标签: python pandas dataframe time


    【解决方案1】:

    我们可以使用merge_asof(df1 是你的 A df2 是你的 B)

    df=pd.merge_asof(df1.sort_values('Date'),df2.sort_values('Week'),left_on='Date',right_on='Week').sort_index(ascending=False).drop('Week',1)
    df
    Out[232]: 
             Date  Price  WeekPrice
    11 2018-01-03  61.63       9782
    10 2018-01-01  60.42       9782
    9  2017-12-29  60.42       9782
    8  2017-12-28  59.84       9754
    7  2017-12-27  59.64       9754
    6  2017-12-26  59.97       9754
    5  2017-12-22  58.47       9754
    4  2017-12-21  58.36       9789
    3  2017-12-20  58.09       9789
    2  2017-12-19  57.97       9789
    1  2017-12-18  57.92       9789
    0  2017-12-17  57.79       9789
    

    【讨论】:

    • 像魅力一样工作!谢谢!
    • @NeelabhPant yw~ :-)
    猜你喜欢
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2023-02-26
    • 2019-08-30
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    相关资源
    最近更新 更多