在熊猫中矢量化连接条件

时间:2017-09-18 06:32:39

标签: pandas

此代码按预期正常工作。但是大型数据帧需要花费大量时间。

for i in excel_df['name_of_college_school'] :
    for y in mysql_df['college_name'] :
        if SequenceMatcher(None,  i.lower(), y.lower() ).ratio() > 0.8:
            excel_df.loc[excel_df['name_of_college_school'] == i, 'dupmark4'] = y

我想,我不能在join子句上使用函数来比较这样的值。 我该如何对此进行矢量化?

更新

是否可以以最高分数进行更新?此循环将覆盖之前的匹配,并且之前的匹配可能比当前匹配更具相关性。

2 个答案:

答案 0 :(得分:2)

您正在寻找的是模糊合并。

a = excel_df.as_matrix()
b = mysql_df.as_matrix()
for i in a:
    for j in b:
        if SequenceMatcher(None,  
               i[college_index_a].lower(), y[college_index_b].lower() ).ratio() > 0.8:
            i[dupmark_index] = j

永远不要在循环中使用loc,它有很大的开销。顺便说一句,得到各列的索引(数字一)。使用此 -

df.columns.get_loc("college name")

答案 1 :(得分:1)

您可以使用apply而不是 MxN .loc操作来避免其中一个循环,现在它将 M 操作。< / p>

for y in mysql_df['college_name']:
    match = excel_df['name_of_college_school'].apply(lambda x: SequenceMatcher(
                                            None, x.lower(), y.lower()).ratio() > 0.8)
    excel_df.loc[match, 'dupmark4'] = y