如何根据Openpyxl中单元格的最大值返回标题的字符串

早上好家伙!Openpyxl 的快速问题:


我正在使用 Python 编辑 xlsx 文档并生成各种统计信息。我的脚本的一部分是生成单元格范围的最大值:


temp_list=[]

temp_max=[]


for row in sheet.iter_rows(min_row=3, min_col=10, max_row=508, max_col=13): 

    print(row)


    for cell in row:

        temp_list.append(cell.value)


    print(temp_list)

    temp_max.append(max(temp_list))

    temp_list=[]

我还希望能够打印包含所需单元格范围最大值的列标题的字符串。我的数据结构如下所示:

http://img.mukewang.com/61a5d8c20001219910310312.jpg

关于如何这样做的任何想法?



慕容3067478
浏览 162回答 3
3回答

慕码人2483693

首先,感谢 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 个标题而不是一个。我的问题是:我怎样才能让这个循环只考虑连续最大值的第一个匹配项?

LEATH

这似乎是一个典型的 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 列表。

蝴蝶不菲

你可能想要这样的东西: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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python