我需要在两个工作表中执行验证以查看两个工作表中是否填充了相同的值。
例如: 在 Sheet1 中,我有一列包含 Product 并且值为 WM001。 在 sheet2 中,我有一个同名 Product 的列,其值为 WM001,然后它是一个 Pass,我什么都不做。
其他情况
例如: 在 Sheet1 中,我有一列包含 Product 并且值为 WM001。 在 sheet2 中,我有一列同名 Product 并且值为 WM00X 然后它失败 我需要输出单元格位置和名称,以便我们可以去更正输入。
我尝试使用合并外连接,但就我而言,我需要比较密钥本身。任何建议。
我需要循环两个数据帧吗?
表 1
产品 |
---|
WM001 |
WM002 |
表 2 |产品 | | -------- | | WM001 | | WM00X |
输出应该表明在 Sheet1 中的任何位置都找不到产品 WM00X,然后输入位置和值 WM00X。
答案 0 :(得分:0)
简单示例
我创建了一个 sample.xlsx 文件来尝试在下面模拟您的情况。 “Sheet1”有一个列产品,“Sheet2”也有。
两列之间的唯一区别是您要识别的记录 2 和 5(从基于零的索引系统开始)(根据那里的索引)。
工作表 1
WM001 | WM00X | WM001 | WM001 | WM00X | WM001 |
Sheet2
WM001 | WM00X | WM00X | WM001 | WM00X | WM00X |
Pandas 允许您直接比较列并创建一个掩码(真值),我们可以使用它来过滤您想要的行。
>>> import pandas as pd
>>> sht1 = pd.read_excel('sample.xlsx', sheet_name='Sheet1')
>>> sht2 = pd.read_excel('sample.xlsx', sheet_name='Sheet2')
# Get the index's of those records that don't match in each sheet
>>> mask = sht1[sht1 != sht2].dropna().index
# Identify those discrepencies in both sheets.
>>> sht1.loc[mask,:]
>>> sht2.loc[mask,:]
注意
最后几行将打印这些记录的索引以及 Product 列中的值。从那里您应该能够识别记录。
如果您想对带有索引值的工作表进行任何就地更改,我建议在 pandas https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iat.html 中使用 .iat[]
。
编辑:
为了处理不同长度的记录,假设索引匹配到表中行数最少的点。很明显,如果sheet1有50行,sheet2有70行,你只能比较两者之间的前50行。
>>> import pandas as pd
>>> sht1 = pd.read_excel('sample.xlsx', sheet_name='Sheet1')
>>> sht2 = pd.read_excel('sample.xlsx', sheet_name='Sheet2')
>>> min_length = min(len(sht1), len(sht2))
>>> sht1_subset = sht1.loc[:min_length,'Product']
>>> sht2_subset = sht2.loc[:min_length,'Product']
# Get the Truth values of those records that don't match on product column in each sheet
>>> mask = (sht1_subset != sht2_subset)
# Identify those discrepencies in both sheets using `mask`
>>> sht1.where(mask).dropna()
>>> sht2.where(mask).dropna()
打印出 mask
看看它返回什么,应该是一系列 True False 值,代表 Product
字段中那些不相等的记录的表达式。