[英]Join two pandas dataframes with only end dates
我有一个包含原始数据的pandas DataFrame,我希望通过添加另一个映射表的查找来丰富它。 映射表将符号转换为另一个符号,但由于存在重复的键,因此它还具有映射的“结束日期”。
要丰富的数据看起来像这样:
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()
函数,然后只获取row_number = 1的行:
select
a.date, d.symbol, d.price, m.to_symbol as mapping,
from (
select
d.date, d.symbol, d.price, m.to_symbol as mapping,
row_number() over(partition by d.date, d.symbol order by m.end_date asc) as rn
from df as d
inner join mapping as m on m.from_symbol = d.symbol and d.date <= m.end_date
) as a
where a.rn = 1
如果date, symbol
上没有重复项,那么DataFrame中的date, symbol
就是:
# merge data on symbols
>>> res = pd.merge(df, mapping, left_on='symbol', right_on='from_symbol')
# remove all records where date > end_date
>>> res = res[res['date'] <= res['end_date']]
# for each combination of date, symbol get only first occurence
>>> res = res.groupby(['date','symbol'], as_index=False, sort=lambda x: x['end_date']).first()
# subset result
>>> res = res[['date','symbol','to_symbol','price']]
>>> res
date symbol to_symbol price
0 2001-01-02 GCF5 GCF05 1000
1 2001-01-02 GCZ5 GCZ15 1001
2 2001-01-03 GCF5 GCF05 1002
3 2001-01-03 GCZ5 GCZ15 1003
4 2001-01-04 GCF5 GCF15 1004
5 2001-01-04 GCZ5 GCZ15 1005
如果可能存在重复项,您可以像上面一样创建DataFrame mapping2
并加入它。
SQL(实际上,SQL Server)的方式是使用outer apply
:
select
d.date, d.symbol, d.price, m.to_symbol as mapping,
from df as d
outer apply (
select top 1
m.to_symbol
from mapping as m
where m.from_symbol = d.symbol and d.date <= m.end_date
order by m.end_date asc
) as m
我不是Pandas的大师,但我认为如果我在mapping
DataFrame上重置索引会更快:
>>> mapping2 = mapping.set_index(['from_symbol', 'end_date']).sort_index()
>>> mapping2
to_symbol
from_symbol end_date
GCF5 2001-01-03 GCF05
2001-12-31 GCF15
GCZ5 2001-12-31 GCZ15
>>> df['mapping'] = df.apply(lambda x: mapping2.loc[x['symbol']][x['date']:].values[0][0], axis=1)
>>> df
date price symbol mapping
0 2001-01-02 1000 GCF5 GCF05
1 2001-01-02 1001 GCZ5 GCZ15
2 2001-01-03 1002 GCF5 GCF05
3 2001-01-03 1003 GCZ5 GCZ15
4 2001-01-04 1004 GCF5 GCF15
5 2001-01-04 1005 GCZ5 GCZ15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.