用Python进行Excel差异比较
我在找一个算法,用来比较两个Excel表格的列名,使用Python来实现。
我不知道这些列具体是什么,所以一个表格可能会有额外的列,或者两个表格中可能有多个列的名字是一样的。
最简单的情况是,第一个表格中的一列只对应第二个表格中的一列。这样我就可以用xlrd
来对那一列的行进行比较。如果列名不唯一,我可以检查这些列的位置是否相同。
有没有人知道有没有现成的算法,或者在这个领域有经验的?
1 个回答
0
快速而简单:
# Since order of the names doesn't matter, we can use the set() option
matching_names = set(sheet_one_names) & set(sheet_one_names)
...
# Here, order does matter since we're comparing rowdata..
# not just if they match at some point.
matching_rowdata = [i for i, j in zip(columndata_one, columndata_two) if i != j]
注意:这假设你已经提前做了一些准备工作,
- 通过
xlrd
获取第一个表的列名,第二个表也是如此, - 将两个表的行数据分别存储在两个不同的变量中。
这样做是为了让你有个大概念。
另外,注意使用 [...] 选项(第二种方法)时,行的长度必须相同,否则会被跳过。这是一种不匹配的情况,反过来获取数据流中的匹配项。
这是一个较慢但可行的解决方案:
column_a_name = ['Location', 'Building', 'Location']
column_a_data = [['Floor 1', 'Main', 'Sweden'],
['Floor 2', 'Main', 'Sweden'],
['Floor 3', 'Main', 'Sweden']]
column_b_name = ['Location', 'Building']
column_b_data = [['Sweden', 'Main', 'Floor 1'],
['Norway', 'Main', 'Floor 2'],
['Sweden', 'Main', 'Floor 3']]
matching_names = []
for pos in range(0, len(column_a_name)):
try:
if column_a_name[pos] == column_b_name[pos]:
matching_names.append((column_a_name[pos], pos))
except:
pass # Index out of range, column length are not the same
mismatching_data = []
for row in range(0, len(column_a_data)):
rowa = column_a_data[row]
rowb = column_b_data[row]
for name, _id in matching_names:
if rowa[_id] != rowb[_id] and (rowa[_id] not in rowb or rowb[_id] not in rowa):
mismatching_data.append((row, rowa[_id], rowb[_id]))
print mismatching_data