我有 .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 連接起來......這樣做的最佳方法是什么?
uj5u.com熱心網友回復:
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" ) ]
根據需要調整檔案路徑和作業表名稱。
uj5u.com熱心網友回復:
選項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'}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314429.html
上一篇:無法訪問嵌套json陣列中的資料
