【问题标题】:Python loop through single cell and column in a csvPython循环遍历csv中的单个单元格和列
【发布时间】:2015-11-20 09:39:17
【问题描述】:

我刚刚学习了 python,我正在尝试将模块 fuzzwuzzy 与 pandas 一起使用来帮助匹配来自 PLACEMENT 和 CREATIVE_NAME 列的名称。

我已经弄清楚如何针对 CREATIVE_NAME 的所有行测试 PLACEMENT 的第一行;但是,我无法弄清楚如何移动到 PLACEMENT 的下一行并针对 CREATIVE_NAME 列进行测试。

我的项目最终目标是打印出每个展示位置值的最佳匹配项以供进一步分析。

df = pd.read_csv(filepath)
fp = df["PLACEMENT"]
tp = df["CREATIVE_NAME"]

score = 0
x=0
y=0
import csv
with open(filepath, 'r') as f:
    reader = csv.DictReader(f)
    for column in reader:
        if score == 0:
            score += fuzz.ratio(fp[x],tp[y])
            if score > 95:
                print "The score is %d"", We have a match!" %(score)
            elif score > 70:
                print "The score is %d"", We have a high likelihood of a match!" %(score)
            elif score > 50:
                print "The score is %d"", The match is not likely!" %(score)
            else:
                print "The score is only %d"", This is not a match!" %(score)
            y += 1
            score = 0

【问题讨论】:

    标签: python pandas iterator iteration


    【解决方案1】:

    您基本上需要将展示位置列中的所有条目与广告素材名称列中的所有条目进行匹配。这可以通过嵌套循环来完成:对于每个展示位置,对于每个广告素材名称,比较展示位置和广告素材名称。

    FuzzyWuzzy 库有一个方便的函数,可用于通过提取最佳匹配的单个函数调用替换内部循环:

    from fuzzywuzzy import process
    
    for placement in fp:
        best_matches = process.extract(placement, tp, limit=3)
        print placement, best_matches
    

    请注意,这需要 n² 比较,其中 n 是数据集中的行数。根据数据集的大小,这可能需要很长时间。

    注意,通过pandas将数据集读入内存后,不需要再打开文件。您对重新打开的文件的循环没有使用column 循环变量(顺便说一下,它应该称为row)。

    【讨论】:

    • 谢谢,代码完美运行!非常感谢您的反馈。是的,我每列大约有 15,000 行。我需要先找到一种方法来对数据进行子集化。 5 行花了将近 20 分钟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多