簡體   English   中英

Pandas 多索引數據幀的條件合並

[英]Conditional merge of Pandas multi-index dataframes

我有兩個數據框。

第一個是客戶的 dataframe,附帶必須在其中完成裝運的月份。

第二個是 dataframe,其中包含范圍內所有可能的日期組合和客戶。 例如,一個為期三天的組合,有一個客戶,'ABC' 從 '2020-01-01' 開始看起來像。

Date        Customer
2020-01-01  'ABC'
2020-01-02  'ABC'
2020-01-03  'ABC'

我正在嘗試加入以下兩個日期框架,以便獲得 customer:dates 的組合,以便日期只能出現在交貨月份內。

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'

所需的 output:

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

我試圖通過mergequery來實現這一點

IE。

ship_dates = df1.merge(df2, left_on='dates', right_on='client')\
                .query('dates >= month')\
                .set_index(['customer','dates'])

但我收到日期的 KeyError。

非常感謝所有幫助!

設法找到解決方案。

我在每個 dataframe 中創建了一個月:年列:

df1['mnth_year'] = pd.to_datetime(df1['dates']).dt.strftime('%B-%Y')
df2['month_year'] = pd.to_datetime(df2['month']).dt.strftime('%B-%Y')

然后合並, using.query() 等於mnth_yrmonth_year

dates = df1.merge(df2, how='inner', left_on='customers', 
                             right_on='customer')\
           .query('mnth_yr == month_year')\
           .set_index(['customer', 'dates'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM