删除包含相邻行的列的重复项,并将重复项附加到上面

时间:2017-11-08 10:42:12

标签: python excel python-3.x openpyxl

我想要复制存在的delete duplicates for Column Ddelete rows adjacent。我想删除差距,以便附加到上面。我在下表中列出了这个。数据的行大小不断变化。我们传统上使用过VBA,但我们现在正在使用Python并且必须改变这部分工作。

有哪些数据:https://ibb.co/gwh0Hb

期待/我想要实现的目标:https://ibb.co/f08Dnb

以下内容倾向于删除重复项并将其放在一列中,但不会删除旁边的重复项旁边的行,并且不会追加列。

代码 -

import openpyxl
wb1 = openpyxl.load_workbook('C:/Users/Documents/dwa.xlsx')
ws1 = wb1.active # keep naming convention consistent
wb2 = openpyxl.load_workbook('C:/Users/Documents/123.xlsx')
ws2 = wb2.active # keep naming convention consistent
values = []
col_e = 6 # easier to remember
values = set() # no duplicates by default; faster 'in' searching
for row in ws1.iter_rows(row_offset=1): # if you have a header
    if row[col_e].value not in values:
        values.add(row[col_e].value)
    else:
        row[col_e].value = '', 
wb2.save('C:/Users/Documents/123.xlsx')

我试图添加 -

values.add(row[col_c].value)以及其他列值,但我还没有取得任何成功。

1 个答案:

答案 0 :(得分:0)

IIUC,这是使用pandas的解决方案:

import pandas as pd
df = pd.read_excel('remove_duplicates.xlsx')
# Identifying duplicates only by column 'C4'
# Further details https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html
df.drop_duplicates(['C4'],keep='first', inplace=True)

输入excel是这样的:

enter image description here

输出将是这样的: enter image description here