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

时间:2017-07-07 21:46:37

标签: python pandas numpy dataframe

以下是我拥有的以下数据框架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

我想通过合并两个数据集来构建一个新的数据框,这两个数据集将具有如下所示的以​​下列,并且如果来自收益惊喜历史记录的reported_time_code是 AMC 那么记录将从库存中引用价格历史应该是第二天。如果reported_time_code是 BM0 ,那么从股票价格历史中引用的记录应该是同一天。如果我在spsh的actual_reported列和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

2 个答案:

答案 0 :(得分:1)

让我们使用np.wheredrop不需要的列,然后merge,根据reported_time_code将新列' 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

答案 1 :(得分:0)

你的偏移量只有一天,真是太棒了。然后你可以做类似以下的事情:

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)