【问题标题】:Intersection in a Loop - python循环中的交叉点 - python
【发布时间】:2018-10-01 13:02:12
【问题描述】:

我需要找到数千个呼叫号码之间的交叉点(目的地号码),即我有以下数据框:

Calling Number | Called Number | Seconds
023456738      | 9123457583    | 55
064785993      | 8804783937    | 125
087594937      | 9123457583    | 34
087594937      | 9278446356    | 33
023456738      | 6547485959    | 45
087594937      | 3547483946    | 23

例如,023456738 拨打了 2 个号码,087594937 拨打了 3 个号码,这个号码 9123457583 是 023456738 和 087594937 这两个号码之间的公共号码。

我想要的输出是:

Calling Number1 | Calling Number2| Intersect Count | Intersect Value
023456738       | 087594937      | 1               | 9123457583

我所做的是我取唯一的主叫号码(使用.unique()),然后放入循环(i,j组合),然后检查i和j之间是否存在公共号码。请看我的代码,merged2 是上面的数据框。 SRC 是主叫号码,DST 是被叫号码。

#library
import pandas as pd
import itertools

merged2.sort_values('DST', inplace=True)

array_src = merged2.SRC.unique()

def intersect(lst1, lst2):
    # Use of hybrid method
    temp = set(lst2)
    lst3 = [value for value in lst1 if value in temp]
    return lst3

df = pd.DataFrame(columns['SRC1','SRC2','Intersect_count','Intersect_value'])


for i, j in itertools.product(array_src, array_src):
    if i == j:
        continue
    dfA = merged2[(merged2['SRC'] == i)].copy()
    array_Adst = dfA.DST.unique()
    dfB = merged2[(merged2['SRC'] == j)].copy()
    array_Bdst = dfB.DST.unique()
    print i,j

    if len(intersect(array_Adst,array_Bdst))>0:
        print i,j
        Intersect_count = len(intersect(array_Adst,array_Bdst))
        Intersect_value = intersect(array_Adst,array_Bdst)
        print Intersect
        #       add them to a dataframe
        lister = [[i, j, Intersect_count,Intersect_value]]
        dfi = pd.DataFrame(lister, columns=['SRC1', 'SRC2','Intersect_count','Intersect_value'])
        df = df.append(dfi)
    else:
        continue

print df.head()

我遇到的问题是运行时间太长,就好像我有 100,000 个主叫号码一样,它会为 100,000C2 的组合执行此操作。例如,它会使用第一个号码 023456738 并检查 064785993、087594937、023456738,然后检查号码 064785993 和 087594937..

您能帮我优化代码吗?谢谢

【问题讨论】:

    标签: python python-2.7 pandas dataframe


    【解决方案1】:

    得到答案:利用矩阵。

    首先在 SRC 和 DST 之间做一个交叉表,然后将其转换为二进制矩阵。然后我们对其进行转置,然后将两者相乘。

    对角线表示每个SRC调用的DST编号的唯一编号,非对角线表示2个SRC之间的DST交集

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多