在自定义条件下合并数据帧的有效方法

2024-09-29 19:36:55 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我拥有的以下数据帧esh->;收益惊喜历史 和sph->;股票价格历史

收益惊喜历史

    ticker   reported_date reported_time_code  eps_actual
0    ABC     2017-10-05       AMC                1.01
1    ABC     2017-07-04       BMO                0.91
2    ABC     2017-03-03       BMO                1.08
3    ABC     2016-10-02       AMC                0.5

股票价格历史

    ticker       date    adj_open   ad_close
0    ABC     2017-10-06   12.10      13.11      
1    ABC     2017-12-05   11.11      11.87     
2    ABC     2017-12-04   12.08      11.40     
3    ABC     2017-12-03   12.01      13.03 
..
101  ABC     2017-07-04   9.01        9.59
102  ABC     2017-07-03   7.89        8.19

我想通过合并两个数据集来构建一个新的数据框架,这两个数据集应具有以下列,如下所示,并且如果收益意外历史中报告的时间代码是AMC,那么从股票价格历史中引用的记录应该是第二天。如果报告的时间代码是BM0,那么股票价格历史记录应在同一天提交。如果我对esh的实际报告列和sph的数据列使用直接合并功能,它将打破上述条件。寻找转换数据的有效方法

这是最终转换的数据集

    ticker       date     adj_open   ad_close  eps_actual
0    ABC     2017-10-06    12.10      13.11      1.01  
101  ABC     2017-07-04    9.01        9.59      0.91

Tags: 数据gtdate报告历史eps收益ticker
2条回答

这是伟大的,你的抵消只有一天。然后您可以执行以下操作:

mask = esh['reported_time_code'] == 'AMC'
# The mask is basically an array of 0 and 1's \
  all we have to do is to convert them into timedelta objects standing for \
  the number of days to offset

offset = mask.values.astype('timedelta64[D]')
# The D inside the bracket stands for the unit of time to which \
  you want to attach your number. In this case, we want [D]ays.

esh['date'] = esh['reported_date'] + offset
esh.merge(sph, on=['ticker', 'date']).drop(['reported_date', 'reported_time_code'], \
                                           axis=1, inplace=True)

让我们根据报告的时间代码,使用np.wheredrop不需要的列,然后merge将一个新列“date”添加到股票价格历史数据框:

eh['reported_date'] = pd.to_datetime(eh.reported_date)

sph['date'] = pd.to_datetime(sph.date)

eh_new = eh.assign(date=np.where(eh.reported_time_code == 'AMC',
                                 eh.reported_date + pd.DateOffset(days=1),
                                 eh.reported_date)).drop(['reported_date','reported_time_code'],axis=1)

sph.merge(eh_new, on=['ticker','date'])

输出:

  ticker       date  adj_open  ad_close  eps_actual
0    ABC 2017-10-06     12.10     13.11        1.01
1    ABC 2017-07-04      9.01      9.59        0.91

相关问题 更多 >

    热门问题