合并不同长度的数据帧

时间:2021-02-24 20:19:55

标签: python dataframe merge vlookup

我正在使用以下代码合并两个不同长度的数据帧:

df1=pd.merge(df1, df2, on='OFFERING_ID',how='left')

合并前的行数为 400 0000,合并后的行数为 600000。

请问如何解决?

谢谢

2 个答案:

答案 0 :(得分:1)

问题不在于长度,而在于 OFFERING_ID

简而言之,OFFERING_ID 在第二个数据框中不是唯一的。因此,每个 OFFERING_ID 会获得多个匹配项,因此比原始行数多。

我在repl.it中做了一个例子,代码也贴在下面:

import pandas as pd

df1 = pd.DataFrame(
    [
        {"OFFERING_ID": 1, "another_field": "whatever"},
        {"OFFERING_ID": 2, "another_field": "whatever"},
        {"OFFERING_ID": 3, "another_field": "whatever"},
        {"OFFERING_ID": 4, "another_field": "whatever"},
    ]
)

df2 = pd.DataFrame(
    [
        {"OFFERING_ID": "1", "another_field": "whatever"},
        {"OFFERING_ID": 1, "another_field": "whatever"},
        {"OFFERING_ID": 1, "another_field": "whatever"},
    ]
)

print(df1.shape)
print(df2.shape)
print(pd.merge(df1, df2, on="OFFERING_ID", how="left").shape)

答案 1 :(得分:1)

offering_id_dfs = []
for id in df1.OFFERING_ID.unique():
    sub_df1 = df1.loc[df1.OFFERING_ID == id , :].reset_index(drop=True)
    sub_df2 = df2.loc[df2.OFFERING_ID == id , :].reset_index(drop=True)
    concat_df = pd.concat([sub_df1, sub_df2], axis=1)
    concat_df["OFFERING_ID"] = id
    offering_id_dfs.append(concat_df)
df3 = pd.concat(offering_id_dfs ).reset_index(drop=True)

只要每个 DataFrame 只包含您的 Offer_ID 旁边的一列,并且所有 df2.Offering_Id.unique() 都在 df1.Offering_Id.unique() 的集合中,这可能会起作用。

相关问题