萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python xlrd 去除 Excel 指定欄位重複值

讀取 Excel 指定欄,利用列表維持順序去重 (保留首次出現順序),適用於資料清洗、字典建立前處理。

核心程式碼


import xlrd

def open_excel(file_name="simple.xls"):
    try:
        return xlrd.open_workbook(file_name)
    except Exception as e:
        print(str(e))
        return None

def scan_excel(sheet_name='Sheet1'):
    wb = open_excel()
    return wb.sheet_by_name(sheet_name) if wb else None

def unique_col(col_index=0):
    sh = scan_excel()
    if not sh: return
    col_vals = sh.col_values(col_index)
    seen = []
    for v in col_vals:
        if v not in seen:
            seen.append(v)
    print("Original:", col_vals)
    print("Unique:  ", seen)

if __name__ == '__main__':
    unique_col()

輸出範例

Original: [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0, 4.0]
Unique:   [1.0, 2.0, 3.0, 4.0]

優化版:使用 OrderedDict / dict (Python 3.7+ 保序)


def unique_col_fast(col_index=0):
    sh = scan_excel()
    if not sh: return
    col_vals = sh.col_values(col_index)
    # Python 3.7+ dict 保證插入順序
    unique = list(dict.fromkeys(col_vals))
    print("Unique:", unique)

時間複雜度從 O(n²) 降為 O(n),大欄位明顯加速。

進階:寫回新 Excel (需 openpyxl/xlsxwriter)


import openpyxl

wb = openpyxl.Workbook()
ws = wb.active
for i, val in enumerate(unique, 1):
    ws.cell(row=i, column=1, value=val)
wb.save('unique_output.xlsx')

注意事項

  • xlrd 2.0+ 僅支援 .xls;.xlsx 請用 openpyxl.load_workbook。
  • 儲存格型別可能為 float (如 1.0),視需求轉 int 或保留字串。
  • 合併儲存格僅主儲存格有值,其餘為空字串,去重時可能需特別處理。
copyright © 萬盛學電腦網 all rights reserved