我有两个数据帧A和B,其中A具有连续数据值,B具有每周一次的值。如何合并两个数据帧,以便B数据帧中的值重复,直到它在A数据帧中到达周末。
实施例: ' A' Dataframe看起来像这样
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
答案 0 :(得分:2)
我们可以使用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