python – 合并pandas数据帧,其中一个值介于两个其他值之间
作者:互联网
参见英文答案 > How to join two dataframes for which column values are within a certain range? 5个
我需要在标识符和条件上合并两个pandas数据帧,其中一个数据帧中的日期在另一个数据帧中的两个日期之间.
Dataframe A有一个日期(“fdate”)和一个ID(“cusip”):
我需要将此与此数据帧B合并:
在A.cusip上== B.ncusip和A.fdate在B.namedt和B.nameenddt之间.
在SQL中这将是微不足道的,但我能看到如何在pandas中执行此操作的唯一方法是首先在标识符上无条件合并,然后在日期条件上进行过滤:
df = pd.merge(A, B, how='inner', left_on='cusip', right_on='ncusip')
df = df[(df['fdate']>=df['namedt']) & (df['fdate']<=df['nameenddt'])]
这真的是最好的方法吗?似乎如果可以在合并中进行过滤以避免在合并之后但在过滤器完成之前具有可能非常大的数据帧,则会好得多.
解决方法:
正如你所说,这在SQL中非常简单,那么为什么不在SQL中呢?
import pandas as pd
import sqlite3
#We'll use firelynx's tables:
presidents = pd.DataFrame({"name": ["Bush", "Obama", "Trump"],
"president_id":[43, 44, 45]})
terms = pd.DataFrame({'start_date': pd.date_range('2001-01-20', periods=5, freq='48M'),
'end_date': pd.date_range('2005-01-21', periods=5, freq='48M'),
'president_id': [43, 43, 44, 44, 45]})
war_declarations = pd.DataFrame({"date": [datetime(2001, 9, 14), datetime(2003, 3, 3)],
"name": ["War in Afghanistan", "Iraq War"]})
#Make the db in memory
conn = sqlite3.connect(':memory:')
#write the tables
terms.to_sql('terms', conn, index=False)
presidents.to_sql('presidents', conn, index=False)
war_declarations.to_sql('wars', conn, index=False)
qry = '''
select
start_date PresTermStart,
end_date PresTermEnd,
wars.date WarStart,
presidents.name Pres
from
terms join wars on
date between start_date and end_date join presidents on
terms.president_id = presidents.president_id
'''
df = pd.read_sql_query(qry, conn)
DF:
PresTermStart PresTermEnd WarStart Pres
0 2001-01-31 00:00:00 2005-01-31 00:00:00 2001-09-14 00:00:00 Bush
1 2001-01-31 00:00:00 2005-01-31 00:00:00 2003-03-03 00:00:00 Bush
标签:date-range,python,pandas,join,timespan 来源: https://codeday.me/bug/20190916/1808597.html