首页 > 解决方案 > 使用 Python 解析 .xlsx 并从行和列中收集内容的统计信息

问题描述

我有 .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 FREE。发现我可以使用 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 连接起来……最好的方法是什么?

标签: pythonexcelparsingxlsxxlrd

解决方案


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" ) ]

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


推荐阅读