3 回答

TA貢獻1860條經驗 獲得超9個贊
首先,感謝 Bernardo 的提示。我找到了一個體面的工作解決方案,但仍然有一個小問題。也許有人可以提供幫助。讓我修改我的初始聲明:這是我現在正在使用的代碼:
temp_list=[]
headers_list=[]
for row in sheet.iter_rows(min_row=3, min_col=27, max_row=508, max_col=32): #Index starts at 1 // Here we set the rows/columns containing the data to be analyzed
for cell in row:
temp_list.append(cell.value)
for cell in row:
if cell.value == max(temp_list):
print(str(cell.column))
print(cell.value)
print(sheet.cell(row=1, column=cell.column).value)
headers_list.append(sheet.cell(row=1,column=cell.column).value)
else:
print('keep going.')
temp_list = []
這個公式有效,但有一個小問題:例如,如果一行有兩次相同的值(即:25,9,25,8,9),這個循環將打印 2 個標題而不是一個。我的問題是:
我怎樣才能讓這個循環只考慮連續最大值的第一個匹配項?

TA貢獻1936條經驗 獲得超7個贊
這似乎是一個典型的 INDEX/MATCH Excel 問題。
您是否嘗試過檢索每個 temp_list 中最大值的索引?
您可以使用 numpy.argmax() 之類的函數來獲取“temp_list”數組中最大值的索引,然后使用此索引來定位標題并將字符串附加到名為“max_headers”的新列表中包含按出現順序排列的所有標題字符串。
它看起來像這樣
for cell in row:
temp_list.append(cell.value)
i_max = np.argmax(temp_list)
max_headers.append(cell(row = 1, column = i_max).value)
等等等等。當然,為了讓它工作,你的 temp_list 應該是一個 numpy 數組而不是一個簡單的 python 列表,并且必須定義 max_headers 列表。

TA貢獻1810條經驗 獲得超4個贊
你可能想要這樣的東西:
headers = [c for c in next(ws.iter_rows(min_col=27, max_col=32, min_row=1, max_row=1, values_only=True))]
for row in ws.iter_rows(min_row=3, min_col=27, max_row=508, max_col=32, values_only=True):
mx = max(row)
idx = row.index(mx)
col = headers[idx]
添加回答
舉報