Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将两个series/df的每个元素与pandas中的自定义函数进行比较,而不使用for循环_Python_Pandas_Longest Substring - Fatal编程技术网

Python 将两个series/df的每个元素与pandas中的自定义函数进行比较,而不使用for循环

Python 将两个series/df的每个元素与pandas中的自定义函数进行比较,而不使用for循环,python,pandas,longest-substring,Python,Pandas,Longest Substring,我构建了一个自定义函数来比较两个url以获得最长的公共子序列(lcs) 我有一个系列s1和一个系列s2,有一堆url(13.000个)。我想比较两个系列的每个元素(169.000.000比较) 我使用了两个嵌套for循环,但速度太慢了 for index1, value1 in s1.items(): for index2, value2 in s2.items(): url1 = value1 url2 = value2 if (inde

我构建了一个自定义函数来比较两个url以获得最长的公共子序列(lcs)

我有一个系列s1和一个系列s2,有一堆url(13.000个)。我想比较两个系列的每个元素(169.000.000比较)

我使用了两个嵌套for循环,但速度太慢了

for index1, value1 in s1.items():
    for index2, value2 in s2.items():
        url1 = value1
        url2 = value2
        if (index1 != index2):
            lcs1 = lcs_dynamic(url1, url2) //usage of my custom function
        overlap = lcs1 /len(url2)
        print({index1}, {index2}, {url1}, {url2}, {overlap})
有更好的方法吗

我考虑了apply()方法,但我不知道如何访问series2和第二个url,因为我的自定义函数lcs_dynamic需要两个url作为参数

series1.apply(lcs_dynamic(url1,url2))
-->在这种情况下,我将从series1获取url1,但如何访问series2和url2。。。不知道


提前谢谢

总结上述评论:

首先,定义包含该系列的两个数据帧:

df1 = pd.DataFrame({'url1' : ['url1/path1/subpath1/subpath2', 'url2/path2/subpath1/subpath2']})
df2 = pd.DataFrame({'url2' : ['url1/path1/subpath1', 'url2/path2/subpath1']})
接下来,执行交叉连接以生成所有可能的组合:

df = df1.merge(df2, how='cross')
接下来,应用自定义函数:

df['lcs'] = df.apply(lambda row : lcs_dynamic(row['url1'], row['url2']), axis = 1)
df['overlap'] = df['lcs'] / df['url2'].str.len()

到目前为止效果很好。但是我怎样才能消除重复的东西呢。当我做交叉连接时,我将得到例如

(1;1), (1;2), (1;3)
(2;1), (2;2), (2;3)

我想删除重复的(1;1)、(2;2)等。。但是重复的(1;2)和(2;1)也一样,因为它们对我来说是一样的。

您正在寻找一种算法来比较序列s1中的每个URL与序列S2中的URL?你想为每个S1找到S2的索引吗?你可以使用apply as
df.apply(lambda行:lcs#U动态(行['series1',行['series2',],轴=1)
@JoeFerndz不,我有这两个的索引。@heretolearn谢谢你的朋友。那么我会得到所有的变量吗?对于所有的变量,我想你必须首先对两个系列进行交叉连接,以生成所有可能的组合,然后为每个工作正常的组合应用自定义函数!但是我丢失了两个系列/数据帧中的索引。现在,我将两个数据帧的索引转换为列,结果成功了!我现在有了一个数据帧:index|u df1 | url1 | index|u df2 | url2 | lcs | overlapp非常感谢!
(1;1), (1;2), (1;3)
(2;1), (2;2), (2;3)