在数据框架中查找无序列表的更快方法

2024-04-20 02:41:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查pandas dataframe行中是否存在新的示例列表

问题是我必须遍历所有测试样本,将每个测试样本(无序列表)与预定义的“有效”数据帧的所有行进行比较

我已经使用2个嵌套for循环和set comparison解决了这个问题,但是每个示例的查找时间几乎为1秒。例如,如果我必须测试1000个样本,那就需要1000秒

此函数用于比较两个列表中的每个元素

from collections import Counter

def compare(s, t):
    if Counter(s) == Counter(t):
        return 1
    else:
        return 0

This look_up function iterate through my valid set and calls compare function to find if a match in the valid set.

def look_up(test):
    freq=0
    for i in range(len(valid_sets)):
        a=valid_sets.iloc[i,0]
        if compare(a,test)==1:
            freq=valid_sets.iloc[i,1]
    if freq>0:
        return "exists"

    else:
        return "missing"

This part loops through samples my test dataframe.
pred_test=[]
for i in range(len(proc_test_df)):
    print("sample point",i)
    sample=proc_test_df.iloc[i,:]
    pred_test.append(look_up(sample))

有人能帮我通过广播或类似的方式得到矢量化的结果或更有效的答案吗。 提前谢谢


Tags: intest列表forreturnifcountersets