首页 > 解决方案 > 比较两个熊猫数据框并根据条件更新一个数据框的最有效方法

问题描述

我有两个数据框 df1 和 df2。df2 由“tagname”和“value”列组成。字典“bucket_dict”保存来自 df2 的数据。

bucket_dict = dict(zip(df2.tagname,df2.value))

在 df1 中有数百万行。df1 中有“apptag”、“comments”和“Type”的 3 列。我想在这两个数据帧之间进行匹配,例如,如果

bucket_dict 中的“字典键”包含在 df1["apptag"] 中,然后更新 df1["comments"] = 对应的字典键和 df1["Type"] = 对应的 bucket_dict["key name"] 的值。我使用了以下代码:

for each_tag in bucket_dict: 
    df1.loc[(df1["apptag"].str.match(each_tag, case = False ,na = False)), "comments"] =  each_tag
    df1.loc[(df1["apptag"].str.match(each_tag, case = False ,na = False)), "Type"] =  bucket_dict[each_tag]

有什么有效的方法可以做到这一点,因为它需要更长的时间。

Bucket df 从中创建了字典:

bucketing_df = pd.DataFrame([["pen", "study"], ["pencil", "study"], ["ersr","study"],["rice","grocery"],["wht","grocery"]], columns=['tagname', 'value'])

其他数据框:

  output_df = pd.DataFrame([["test123-pen", "pen"," "], ["test234-pencil", "pencil"," "], ["test234-rice","rice", " "], columns=['apptag', 'comments','type'])

所需输出: 在此处输入图像描述

标签: python-3.xpandas

解决方案


您可以通过以这种方式在您的comments列上调用应用程序以及在您的列上调用来做到这一点 -locbucketing_df

def find_type(a):
    try:
        return (bucketing_df.loc[[x in a for x in bucketing_df['tagname']]])['value'].values[0]
    except:
        return ""

def find_comments(a):
    try:
        return (bucketing_df.loc[[x in a for x in bucketing_df['tagname']]])['tagname'].values[0]
    except:
        return ""


output_df['type'] = output_df['apptag'].apply(lambda a: find_type(a))
output_df['comments'] = output_df['apptag'].apply(lambda a:find_comments(a))

在这里,我必须使它们成为单独的功能,以便它可以处理不tagname存在的情况apptag

它给你这个output_df-

           apptag comments     type
0     test123-pen      pen    study
1  test234-pencil   pencil    study
2    test234-rice     rice  grocery

All this code uses is the existing bucketing_df and output_df you provided at the end of your question.


推荐阅读