【问题标题】:How can i merge dataframes based on a day and month range?如何根据日期和月份范围合并数据框?
【发布时间】:2021-05-25 06:24:21
【问题描述】:

我有如下表A和表B:

表 A

     from      to   comercial_event
0   01/07   02/07   January sales
1   02/12   02/12   Chinese new year
2   02/13   02/18   Carnival
3   02/07   02/14   Valentine's Day
4   03/12   03/19   Father's day

表 B

                        dates   comercial_event     month_day
0   2017-01-14 23:01:10+00:00           unknown         01/14
1   2017-08-29 23:01:10+00:00           unknown         08/29
2   2017-02-13 23:01:10+00:00           unknown         02/13
3   2017-08-31 23:01:10+00:00           unknown         08/31
4   2017-03-15 23:01:10+00:00           unknown         03/15

我想要做的是使用表 B 中的 month_day 列作为参考来合并 2 个表。 month_day 列仅表示月份和日期(没有年份)。如果此列的值介于表 A 的列 fromto 的值之间,则表 B 的 comercial_event 列应使用表 A 的 comercial_event 列的值更新为该范围月和日。输出将是这样的:

                            dates   comercial_event     month_day
    0   2017-01-14 23:01:10+00:00   January Sales           01/14
    1   2017-08-29 23:01:10+00:00           unknown         08/29
    2   2017-02-13 23:01:10+00:00   Valentine's Day         02/13
    3   2017-08-31 23:01:10+00:00           unknown         08/31
    4   2017-03-15 23:01:10+00:00   Father's day            03/15

如果month_day 值与多个商业事件同时发生,则comercial_event 列值应为“多个”。

我见过this 问题和this 问题,但似乎都没有真正解决这个问题。

我正在使用python 2.7pandas 0.24

我该如何解决这个问题?

【问题讨论】:

标签: python pandas python-2.7 date merge


【解决方案1】:

让我们做

idx = pd.IntervalIndex.from_arrays(pd.to_datetime(df1['from'], format='%m/%d'),
           pd.to_datetime(df1['to'],format='%m/%d'), 'both')
s = pd.Series(df1.comercial_event.tolist(), index=idx)
look = pd.to_datetime(df2['month_day'], format='%m/%d')

l = []
for x in look:

    try:
        l.append(s.loc[[x]].tolist())
    except:
        l.append(np.nan)
df2['out'] = l
df2
Out[117]: 
        dates comercial_event month_day                         out
0  2017-01-14         unknown     01/14              [Januarysales]
1  2017-08-29         unknown     08/29                         NaN
2  2017-02-13         unknown     02/13  [Carnival, Valentine'sDay]
3  2017-08-31         unknown     08/31                         NaN
4  2017-03-15         unknown     03/15               [Father'sday]

【讨论】:

  • 嗨@BENY,非常感谢您的回答。虽然它看起来很实用,但它并没有完全符合我的要求,此外它很难阅读,但我认为应该这样做。再次非常感谢您
猜你喜欢
  • 2015-09-28
  • 2018-11-14
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
相关资源
最近更新 更多