我有两个数据框。
第一个是客户的数据框,其中包含必须在一个月内完成发货的月份。
第二个是一个数据框,其中包含地平线内日期和客户的所有可能组合。例如,一个三天的视界组合,其中有一个客户,从“ 2020-01-01”开始的“ ABC”看起来像这样。
Date Customer
2020-01-01 'ABC'
2020-01-02 'ABC'
2020-01-03 'ABC'
我正在尝试加入以下两个日期框架,以便获得customer:date的组合,这样日期只能在交货月份之内出现。
df_a.head(5)
>>> month, client
2020-01 'ABC'
'DEF'
2020-02 'GHI'
'JKL'
'MNO'
2020-03 'PQR'
df_b.head(5)
>>> dates client
'2020-01-01' 'ABC'
'2020-01-01' 'DEF'
'2020-01-02' 'ABC'
'2020-01-02' 'DEF'
'2020-01-03' 'ABC'
'2020-01-03' 'DEF'
所需的输出:
df_joined.head(5)
customer dates
'ABC' 2020-01-01
'ABC' 2020-01-02
'ABC' 2020-01-03
'DEF' 2020-01-01
'DEF' 2020-01-02
'DEF' 2020-01-03
'GHI' 2020-02-01
'GHI' 2020-02-02
'GHI' 2020-02-03
'JKL' 2020-02-01
'JKL' 2020-02-02
'JKL' 2020-02-03
我尝试使用merge
和query
即。
ship_dates = df1.merge(df2, left_on='dates', right_on='client')\
.query('dates >= month')\
.set_index(['customer','dates'])
但是我收到日期的KeyError。
非常感谢所有帮助!
答案 0 :(得分:0)
设法找到解决方案。
我在每个数据框中创建了month:year列:
df1['mnth_year'] = pd.to_datetime(df1['dates']).dt.strftime('%B-%Y')
df2['month_year'] = pd.to_datetime(df2['month']).dt.strftime('%B-%Y')
然后使用.query()合并mnth_yr
与month_year
并合并:
dates = df1.merge(df2, how='inner', left_on='customers',
right_on='customer')\
.query('mnth_yr == month_year')\
.set_index(['customer', 'dates'])