python-3.x - 比较两个熊猫数据框并根据条件更新一个数据框的最有效方法
问题描述
我有两个数据框 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'])
解决方案
您可以通过以这种方式在您的comments
列上调用应用程序以及在您的列上调用来做到这一点 -loc
bucketing_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.
推荐阅读
- java - 如何忽略 RDD 字符串的一部分进行操作
- javascript - 使用 JSON 创建表格并对其进行样式化
- c++ - glm c++ 在每个循环上输出差值
- android - 使用自签名证书签署应用程序是否会影响哪些 Android 设备可以在 Play 商店中看到该应用程序?
- list - 列出埃隆马斯克推文情感分析中超出范围的索引
- node.js - WebRTC 对等服务器连接
- python - 如何在不重新运行程序的情况下在 tkinter 表上显示新的添加数据?
- rust - 如何将函数存储在结构中,然后在其他地方使用?
- python - 在我的情况下,如何使用 sqlite3 更新 UNIQUE 值?
- math - 如何找到一个整数乘数以达到 10 的幂?