簡體   English   中英

合並不同長度的dataframe

[英]Merge dataframe with different lengths

我正在使用以下代碼合並兩個不同長度的數據幀:

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

合並前的行數為 400 0000,合並后的行數為 600000。

請問你怎么解決?

謝謝

問題不在於長度,而在於OFFERING_ID

簡而言之, OFFERING_ID在第二個 dataframe 中不是唯一的。 因此,每個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)
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 在您的 Offering_ID 旁邊僅包含一列並且所有 df2.Offering_Id.unique() 都在 df1.Offering_Id.unique() 的集合中,這可能會起作用。

暫無
暫無

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

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