【问题标题】:Pandas read (Excel) columns of texts, and return similarity ratioPandas 读取 (Excel) 文本列,并返回相似率
【发布时间】:2019-08-11 09:44:42
【问题描述】:

Excel 列如下。我想检查 B 列中的内容与 A 列中的那些文本的最大相似度。

A 列有几个用“;”分隔的字符串 B 列只有 1 个字符串

这是我想出的 xlrd 和 xlwt。

import xlwt, xlrd
from difflib import SequenceMatcher

workbook = xlrd.open_workbook("C:\\file.xlsx")
old_sheet = workbook.sheet_by_index(0)

book = xlwt.Workbook(encoding='cp1252', style_compression = 0)
sheet = book.add_sheet('Sheet1', cell_overwrite_ok = True)

for row_index in range(0, old_sheet.nrows):
    new_list = []   
    Cell_a = old_sheet.cell(row_index, 0).value
    Cell_b = old_sheet.cell(row_index, 1).value

    Cell_a_list = Cell_a.split("; ")
    ratio_list = []
    for each in Cell_a_list:

        ratio = SequenceMatcher(None, each, Cell_b).ratio()
        ratio_list.append(ratio)

    Cell_c = max(ratio_list)

    sheet.write(row_index, 0, Cell_a)
    sheet.write(row_index, 1, Cell_b)
    sheet.write(row_index, 2, Cell_c)

book.save("C:\\file-1.xls")

除了下图,Pandas 的方式看起来如何?谢谢。

import pandas as pd


data = {'Column_a' : ["Spaghetti, BL; Pasta, without eggs, WKB; Pasta, without eggs, BL; Pasta, with eggs, WKB",
"Noodles, instant, portion pack, WKB; Vermicelli (Angel Hair), BL; Beef, fillet, tenderloin (H2)",
"Beef, center brisket (B2); Beef, center brisket, with bones (B2); Beef, Silverside (F2a); Beef, Sirloin steak (H1)",
"Beef, minced; Beef/pork, minced; Veal, breast (D1), with bones; Veal, schnitzel/escalope (A5)",
"Pork, fillet, tenderloin (B); Pork, schnitzel/escalope (AA)"], 
'Column_b' : ["Fresh tortellini or ravioli, WKB",
"Beef, rumpsteak (H3)",
"Beef, shreds or dices (H3, F)",
"Veal, loin (B2)",
"Pork, schnitzel/escalope (A)"]}

df = pd.DataFrame(data)

【问题讨论】:

    标签: python pandas similarity


    【解决方案1】:

    在 pandas 中,您可以直接读取 excel(文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
    假设您阅读了您的 excel 以获取包含 AB 列的数据框 df。然后你可以简单地写:

    def calc_ratio(a,b):
        return max([SequenceMatcher(None, each, Cell_b).ratio() for each in a.split("; ")])
    df["c"] = df.apply(calc_ratio, axis=1)
    

    要将输出写回 excel,请使用 df.to_excel。有关详细文档,请参阅此处https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多