熊猫阅读(Excel)文本列,并返回相似率

时间:2019-08-11 09:44:42

标签: python pandas similarity

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

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

enter image description here

这就是我想出的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")

除了下面的内容外,熊猫的样子如何?谢谢。

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)

1 个答案:

答案 0 :(得分:0)

在熊猫中,您可以直接阅读excel(文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
假设您已阅读Excel,以获取具有列dfA的数据框B。然后,您可以简单地编写:

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