【发布时间】:2017-10-21 06:07:03
【问题描述】:
我有 2 个熊猫数据框。我想在 2 个数据帧之间进行查找和替换。在df_find 数据帧的 current_title 列中,我想在每一行中搜索df_replace 数据帧中“keywrod”列中出现的任何值,如果找到,将其替换为“keywordlength”中的相应值' 列。
我已经能够摆脱df_find 数据帧的循环,因为我需要使用str.replace 迭代此数据帧中的每一行,str.replace 是replace 函数的矢量化形式。
在我的情况下,性能很重要,因为两个数据帧都运行在 GB 中。所以,我想在这里摆脱df_replace 的循环,并使用任何其他有效的方法来遍历df_replace 数据帧的所有行。
import pandas as pd
df_find = pd.read_csv("input_find.csv")
df_replace = pd.read_csv("input_replace.csv")
#replace
for i,j in zip(df_replace.keyword,df_replace.keywordLength):
df_find.current_title=df_find.current_title.str.replace(i,j,case=False)
df_replace 该数据框包含我们查找和替换所需的数据
keyword keywordLength
IT Manager ##10##
Sales Manager ##13##
IT Analyst ##12##
Store Manager ##13##
df_find 是我们需要进行转换的地方。
在执行查找和替换代码之前:
current_title
I have been working here as a store manager since after I passed from college
I am sales manager and primarily work in the ASEAN region. My primary rolw is to bring new customers.
I initially joined as a IT analyst and because of my sheer drive and dedication, I was promoted to IT manager position within 3 years
通过上述代码执行查找和替换后
current_title
I have been working here as a ##13## since after I passed from college
I am ##13## and primarily work in the ASEAN region. My primary rolw is to bring new customers.
I initially joined as a ##12## and because of my sheer drive and dedication, I was promoted to ##10## position within 3 years
我将永远感激不尽!谢谢
【问题讨论】:
-
匹配的值是完全匹配,还是只有子字符串匹配?如果有多个匹配项怎么办?你只参加第一场比赛吗?
-
替换所有匹配项。完全匹配。
-
查看正则表达式和
re.sub。您可以将文件作为文本读取,将要替换的内容替换为正则表达式,然后以 csv 格式打开。 -
str.replace 是 re-sub 的矢量化实现。它对整列而不是单行执行操作。
标签: python performance pandas for-loop vectorization