Skip to main content
 首页 » 编程设计

python之合并两个 pandas DataFrame,其中日期字段在两个月内

2025年02月15日8rubylouvre

我需要合并 2 个 pandas 数据帧,其中 df1.date 在 df2 之前的 2 个月内。然后我想计算在此期间有多少交易者交易了同一只股票,并计算购买的股票总数。

我尝试过使用下面列出的方法,但发现它太复杂了。我相信会有更智能/更简单的解决方案。

Pandas: how to merge two dataframes on offset dates?

示例数据集如下:

DF1(team_1):

date        shares  symbol  trader 
31/12/2013  154     FDX     Max 
30/06/2016  2367    GOOGL   Max 
21/07/2015  293     ORCL    Max 
18/07/2015  304     ORCL    Sam 

DF2(team_2):

date        shares  symbol  trader 
23/08/2015  345     ORCL    John 
04/07/2014  567     FB      John 
06/12/2013  221     ACER    Sally 
31/11/2012  889     HP      John 
05/06/2010  445     ABBV    Kate 

要求的输出:

date        shares  symbol  trader  team_2_traders  team_2_shares_bought 
23/08/2015  345     ORCL    John    2               597 
04/07/2014  567     FB      John    0               0 
06/12/2013  221     ACER    Sally   0               0 
31/11/2012  889     HP      John    0               0 
05/06/2010  445     ABBV    Kate    0               0 

这增加了 2 个新列... 'team_2_traders' = 在 DF2 上列出的日期起的前 2 个月内,team_1 中有多少交易员交易了同一只股票。 'team_2_shares_bought' = team_1 在前 2 个月内从 DF2 上列出的日期起购买的股票总数。

如果有人愿意对此进行破解,请使用下面的代码片段来设置数据框。请记住,实际数据集包含数百万行和 6,000 家公司股票。

team_1 = {'symbol':['FDX','GOOGL','ORCL','ORCL'],  
          'date':['31/12/2013','30/06/2016','21/07/2015','18/07/2015'],  
          'shares':[154,2367,293,304], 
          'trader':['Max','Max','Max','Sam']} 
df1 = pd.DataFrame(team_1) 
 
team_2 = {'symbol':['ORCL','FB','ACER','HP','ABBV'], 
          'date':['23/08/2015','04/07/2014','06/12/2013','31/11/2012','05/06/2010'], 
          'shares':[345,567,221,889,445], 
          'trader':['John','John','Sally','John','Kate']} 
 
df2 = pd.DataFrame(team_2) 

感谢您的帮助 - 谢谢。

请您参考如下方法:

请检查我的解决方案。

from pandas.tseries.offsets import MonthEnd 
 
df_ = df2.merge(df1, on=['symbol']) 
df_['date_x'] = pd.to_datetime(df_['date_x']) 
df_['date_y'] = pd.to_datetime(df_['date_y']) 
 
df_2m = df_[df_['date_x'] < df_['date_y'] + MonthEnd(2)] \ 
        .loc[:, ['date_y', 'shares_y', 'symbol', 'trader_y']] \ 
        .groupby('symbol') 
 
df1_ = pd.concat([df_2m['shares_y'].sum(), df_2m['trader_y'].count()], axis=1) 
 
print(df1_) 
 
        shares_y  trader_y 
symbol                     
ORCL         597         2 
 
print(df2.merge(df1_.reset_index(), on='symbol', how='left').fillna(0)) 
 
         date  shares symbol trader  shares_y  trader_y 
0  23/08/2015     345   ORCL   John     597.0       2.0 
1  04/07/2014     567     FB   John       0.0       0.0 
2  06/12/2013     221   ACER  Sally       0.0       0.0 
3  30/11/2012     889     HP   John       0.0       0.0 
4  05/06/2010     445   ABBV   Kate       0.0       0.0