使用 Python 解析 .xlsx 并从行和列中收集内容统计信息

Parse .xlsx with Python and gather statistic of contents from rows and columns

我有如下所示的 .xlsx 文件:

  ID      Column1    Column2    Column3   ...

  123      Free       BLUE       XX
  333       NA        GREEN      X
  445      BUSY       BLUE       XX
  665      FREE       BLUE       XXX
  332       NA        RED        X
  297      FREE       BLUE       XXXX 
  ...      ...        ...        ...

所以我必须制作一个 python 脚本来加载这个文件并解析它并给我所有的 ID,例如 Column1 是免费的。发现我可以使用像 xlrd、pandas、Openpyxl 等库。但仍然无法实现我需要的东西。

我目前对 xlrd 的尝试是这样的:

  file_location = 'location'
    workbook = xlrd.open_workbook(file_location)
    
    sheet = workbook.sheet_by_name('wanted_sheet')
    
    IDs = []
    col1 = []
    for id in sheet.col_values(0):
        IDs.append(id)
    
    for state in sheet.col_values(1):
       if state == 'FREE':
         col1.append(state)

现在需要以某种方式将此状态与相应的 ID 连接...执行此操作的最佳方法是什么?

import pandas as pd

df = pd.read_excel(
    io = "R:/x.xlsx" ,
    # sheet_name = 0 , # 1st sheet ,
    sheet_name = "Sheet1" ,
    )

df[ ( df["Column1"]=="Free" ) | ( df["Column1"]=="FREE" ) ]

根据需要调整文件路径和工作表名称。

选项 1

使用pandas。 @wenyongzhou 已经给你解答了

选项 2

如果出于任何原因您不得不不用 pandas,只需使用 openpyxl 或其他库并读取 dict 中的行。为了有一些过滤选项,我们可以定义一个小函数:

wb=load_workbook("yourfile.xlsx")
ws=wb.active

def filter_rows(ws, filtercolumn, filtervalue):
    headers = [h.value for h in next(ws.rows)]
    filterindex = headers.index(filtercolumn)
    return {r[0].value : r[filterindex].value for r in ws.rows if r[filterindex].value == filtervalue}

filter_rows(ws,"Column1","FREE")
{665: 'FREE', 297: 'FREE'}

filter_rows(ws,"Column2","BLUE")
{123: 'BLUE', 445: 'BLUE', 665: 'BLUE', 297: 'BLUE'}