【问题标题】:Concatenate dataframe rows and match when key is the same连接数据帧行并在键相同时匹配
【发布时间】:2016-06-12 18:59:25
【问题描述】:

我有两个数据框,df1 和 df2,我正在尝试找出一种生成 df3 的方法,如屏幕截图所示:

因此,这里的目标是保留 df1 的所有行并在其下附加 df2 的行。但是,我想要一行来匹配姓名、纬度和经度。因此,Name、Lat 和 Lon 将用作键。

还有 ZIP 专栏的问题。对于连接的行,我想保留 df1 的 ZIP 值。

我试过了:

df3=pandas.merge(df1,df2,on=['Name','Lat','Lon'],how='outer')

这产生了接近我想要的东西:

如您所见,上面的数据框包含两个不同的 ZIP 和地址列。

知道如何获取干净的 df3 数据框吗?

【问题讨论】:

    标签: python pandas merge concatenation


    【解决方案1】:

    我认为“合并”不适合此任务(即,将左 DF 连接到右 DF),因为您实际上是将一个 DF 放在另一个 DF 之上,然后删除重复项。所以你可以试试这样的:

    #put one DF 'on top' of the other (like-named columns should drop into place)
    df3 = pandas.concat([df1, df2])
    #get rid of any duplicates
    df3.drop_duplicates(inplace = True)
    

    编辑

    根据您的反馈,我意识到需要更肮脏的解决方案。您将使用合并,然后从重复的列中填充 NaN。类似的东西

    df1 = pd.DataFrame({'test':[1,2,3,6,np.nan, np.nan]})
    df2 = pd.DataFrame({'test':[np.nan,np.nan,3,6,10,24]})
    
    #some merge statement to get them into together into the var 'df'
    df = pd.merge(df1, df2, left_index = True, right_index=True)
    
    #collect the _x columns
    original_cols = [x for x in df.columns if x.endswith('_x')]
    
    for col in original_cols:
        #use the duplicate column to fill the NaN's of the original column
        duplicate = col.replace('_x', '_y')
        df[col].fillna(df[duplicate], inplace = True)
    
        #drop the duplicate
        df.drop(duplicate, axis = 1, inplace = True)
    
        #rename the original to remove the '_x'
        df.rename(columns = {col:col.replace('_x', '')}, inplace = True)
    

    让我知道这是否可行。

    【讨论】:

    • 对不起,我不得不接受你的回答。我意识到这不是我想要的。例如,Clocks 需要从两个数据帧中获取评论和公共列的值。所以,应该有一个合并操作。
    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2020-04-09
    • 2013-10-18
    相关资源
    最近更新 更多