【问题标题】:Compare two data-frames with different column names and update first data-frame with the column from second data-frame比较具有不同列名的两个数据框,并使用来自第二个数据框的列更新第一个数据框
【发布时间】:2021-08-14 05:46:20
【问题描述】:

我正在处理两个具有不同列名和维度的数据框。

第一个数据帧“df1”包含单列“名称”,其名称需要位于第二个数据帧中。如果匹配,则需要返回 df2 第一列 df2[0] 中的值并添加到 result_df 中

第二个数据框“df2”有多个列,没有标题。这包含所有可能的小名和全名。任何列都可以有需要匹配的“名称”

目标:在“df2”中找到“df1”中的名称,如果匹配,则返回df2第一列的值并添加到df1的相应行中

df1

name
ab
alex
bob
robert
bill

df2

0 1 2 3
abram ab
robert rob bob robbie
alexander alex al
william bill

result_df

name matched_name
ab abram
alex alexander
bob robert
robert robert
bill william

到目前为止我编写的代码出错了。我需要将其编写为高效代码,因为它将使用 df2 检查 df1 中的数百万个条目:

''' result_df = process_name(df1, df2)

定义进程名称(df1,df2):

for elem in df2.values:
    
    if elem in df1['name']:
        df1["matched_name"] = df2[0]

'''

【问题讨论】:

    标签: python pandas dataframe compare


    【解决方案1】:

    通过concat(),merge(),drop() 和rename() 和reset_index() 方法尝试:

    df=(pd.concat((df1.merge(df2,left_on='name',right_on=x) for x in df2.columns))
        .drop(['1','2','3'],1)
        .rename(columns={'0':'matched_name'})
        .reset_index(drop=True))
    

    df的输出:

        name    matched_name
    0   robert  robert
    1   ab      abram
    2   alex    alexander
    3   bill    william
    4   bob     robert
    

    【讨论】:

    • 谢谢,它成功了。由于数据类型不同,重命名不起作用,所以我转换了数据类型。
    • @Samy 哦……太好了……顺便说一句,如果此答案对您有所帮助,那么请尝试考虑接受该答案以表明其他人问题已解决……谢谢: )
    猜你喜欢
    • 2020-03-21
    • 2021-12-01
    • 1970-01-01
    • 2021-06-06
    • 2018-09-27
    • 2022-09-22
    • 2021-01-11
    • 2019-03-29
    • 2019-06-26
    相关资源
    最近更新 更多