我有一个包含原始数据的pandas数据框,我想通过添加另一个映射表的查找来丰富它。映射表将一个符号转换为另一个符号,但由于存在重复的键,因此它还具有映射的“结束日期”。你知道吗
要充实的数据如下所示:
date symbol price
0 2001-01-02 00:00:00 GCF5 1000.0
1 2001-01-02 00:00:00 GCZ5 1001.0
2 2001-01-03 00:00:00 GCF5 1002.0
3 2001-01-03 00:00:00 GCZ5 1003.0
4 2001-01-04 00:00:00 GCF5 1004.0
5 2001-01-04 00:00:00 GCZ5 1005.0
映射表如下所示:
from_symbol to_symbol end_date
0 GCF5 GCF05 2001-01-03 00:00:00
1 GCF5 GCF15 2001-12-31 00:00:00
2 GCZ5 GCZ15 2001-12-31 00:00:00
我希望输出像这样:
date symbol mapped price
0 2001-01-02 00:00:00 GCF5 GCF05 1000.0
1 2001-01-02 00:00:00 GCZ5 GCZ15 1001.0
2 2001-01-03 00:00:00 GCF5 GCF05 1002.0
3 2001-01-03 00:00:00 GCZ5 GCZ15 1003.0
4 2001-01-04 00:00:00 GCF5 GCF15 1004.0
5 2001-01-04 00:00:00 GCZ5 GCZ15 1005.0
我已经研究了Series.asof()
和ordered_merge()
函数,但是我看不到如何在symbol == from_symbol
子句上同时连接,并使用end_date
来查找第一个条目。end_date
对于连接是包含的。你知道吗
谢谢你, 乔恩
不知道是否有更优雅的方法可以做到这一点,但目前我看到了两种方法(我主要使用SQL,所以这些方法都是从这个背景中获得的,因为
join
实际上是从关系数据库获得的,所以我还将添加SQL语法):加入,然后坐第一排。
SQL方法是使用
row_number()
函数,然后只获取行数=1的行:如果数据帧中的
date, symbol
上没有重复项,那么:如果有可能是重复的,您可以像上面那样创建DataFrame
mapping2
,并加入其中。你知道吗应用
SQL(实际上,SQL Server)的方法是使用
outer apply
:我不是Pandas的专家,但我认为如果我在
mapping
数据帧上重置索引会更快:相关问题 更多 >
编程相关推荐