pandas 在多个键上进行外连接

问题描述 投票:0回答:1

merged_df = pd.merge(左= df1,右= df2,on = [“id”,“日期”],how =“外部”)

假设数据 -

df1-

id 日期 值1
101 2021-01-01 200
101 2021-01-03 400

df2-

id 日期 值2
101 2021-01-01 600
101 2021-01-02 900

我的预期结果是-

id 日期 值1 值2
101 2021-01-01 200 600
101 2021-01-02 NaN 900
101 2021-01-03 400 NaN

当前结果 -

id 日期 值1 值2
101 2021-01-01 200 600
101 2021-01-03 400 NaN

我无法弄清楚哪里出了问题。

编辑 01:当 df1 中不存在 df2 行时,它看起来好像缺少 df2 行。

更改向左和向右的方式可以按预期工作,但是当涉及到外部时,它无法按预期工作。

python-3.x pandas
1个回答
0
投票

我今天遇到了同样的问题。我通过查看 ID 列来检查连接的输出...但是 pandas 在合并过程中填充了左侧的 ID 列。在下面的示例中,

customer_id=10
不在
customers
数据框中,但它仍然出现在连接之后。

import pandas as pd

# Prep data
df_customers = pd.DataFrame({
    ('customers', 'customer_id') : [1, 2, 3, 4, 5],
    ('customers', 'customer_name'): ['Salvador', 'Gilbert', 'Alice', 'Eric', 'John'],
})
df_orders = pd.DataFrame( {
    ('orders', 'order_id'): [1, 2, 3, 4],
    ('orders', 'customer_id'): [1, 2, 3, 10],
    ('orders', 'total_amount'): [150, 200, 100, 50]
}
)

# Perform joins
left = pd.merge(
    df_customers, 
    df_orders, 
    left_on=[('customers', 'customer_id')], 
    right_on=[('orders', 'customer_id')], 
    how='left'
)
right = pd.merge(
    df_customers, 
    df_orders, 
    left_on=[('customers', 'customer_id')], 
    right_on=[('orders', 'customer_id')], 
    how='right'
)
outer = pd.merge(
    df_customers, 
    df_orders, 
    left_on=[('customers', 'customer_id')], 
    right_on=[('orders', 'customer_id')], 
    how='outer',
)

# Display the counts
len(left), len(right), len(outer)
print(outer)  # Note that customer_id = 10 is suddenly part of (customers, customer_id)

© www.soinside.com 2019 - 2024. All rights reserved.