python - Pandas 读取(Excel)文本列,并返回相似度

标签 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")

除了下面的内容之外,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)

最佳答案

在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

关于python - Pandas 读取(Excel)文本列,并返回相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57448933/

相关文章:

python - 为什么python3k的pyserial返回字节而python2k返回字符串?

python - 来自 Pandas Edgelist 数据帧的无向图的邻接矩阵

python - 多索引合并返回空 df 但连接应该有效

python - Pandas :如何 groupby/pivot 保留 NaNs?将 float 转换为 str 然后再转换回 float 有效但看起来很复杂

c++ - 如何计算 mahadistance 的协变矩阵

r - 数据框中每两行之间的余弦相似度

python - 如何计算字符串python中的句点字母

python - Tensorflow:张量的单个元素连接期间出现 ZeroDivisionError

python - 使用 Groupby 将 value_counts 存储在 Dask Dataframe 的新列中

python - 从 gensim 解释负 Word2Vec 相似度