比较excel和文本文件中相同数据的最佳方法

2024-09-22 20:21:31 发布

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

如何在Python中执行以下操作:让我比较文本文件和excel文件,看看它们是否包含相同的数据?我有下面的代码(底部)设置,它只查找模型,如果它在文本文件中,它会打印出模型,品牌和类型在那里,但有时有多个相同的模型(不要问为什么),所以我如何输出

我宁愿让它从excel表格中取出一行/单元格,并将其与文本文件的每一行进行比较,如果其中包含相同的数据,则打印出这两行,但我不确定如何执行该操作。另外,如果excel中有一个空行,我怎么跳过它呢

我有一个包含以下内容的文本文件

Toyota sedan Corrola
Honda sedan Accord
Honda SUV CR-V
Toyota sedan Camry
Toyota sedan Avalon
Honda SUV Camry

以及包含以下内容的excel文件:

enter image description here

代码:

import pandas as pd
file1 = 'cars.xls'
file2 = open("cars.txt", "r")
df = pd.read_excel(file1, header=0)  
readfile = file2.read()

for count in range(len(df['Brand'])):
    if not str(df['Brand'][count]):
        print("Blank line" + str(count))
        print()
        continue

    model = str(df['model'][count])
    model2 = model.replace(' ', '')  # get rid of spaces in case there are any

    if model2 in readfile:
        print(str(df['Brand'][count]) + str(df['type'][count]) + str(df['model'][count]) + " is in both Excel sheet and text file")

期望输出:(无特定订单) 丰田轿车Corrola位于Excel表格和文本文件中 本田SUV CR-V位于Excel表格和文本文件中 丰田轿车凯美瑞位于Excel表格和文本文件中 本田SUV凯美瑞位于Excel表格和文本文件中 日产轿车Altima不在Excel表格和文本文件中

等 等


Tags: in模型dfmodelcountexcel表格文本文件
1条回答
网友
1楼 · 发布于 2024-09-22 20:21:31

将文本文件的内容转换为数据框,然后检查它们是否相等。您可以调整如下内容:

df = pd.DataFrame({"Brand": ["Toyota","Honda",0,"Nissan"],
              "type": ["sedan", "SUV", 0, "sedan"],
              "model": ["Camry", "CR-V", 0, "Altima"]})


df_2 = pd.DataFrame({"Brand": ["Toyota","Honda","Honda","0"],
                  "type": ["sedan", "sedan", "SUV", "0"],
                  "model": ["Honda", "SUV", "CR-V", "0"]})

df == df_2

#output
 Brand   type  model
0   True   True  False
1   True  False  False
2  False  False  False
3  False  False  False

相关问题 更多 >