首页 文章

读取Excel文件并仅使用特定文件

提问于
浏览
0

在我过去的问题中,我已经说过我是python的新手 . 我只用过一次工作 . 而且,我必须做一个小工作来完成工作 .

我必须读取一个excel文件,在那个excel文件中,有3列(col1,col2,col3) . 大约有100行 .

col1有2个值A和B. col2的值范围为ONLY 1 - 10. col3,有很多不同的值 .

但我希望我的python程序查看col1中的每个不同值,然后查看col2中的每个不同值,然后计算col3的所有相应值的avg .

希望输出看起来像这样:

A - 1 = 2.3
A - 2 = 6.2
A - 3 = 5.7
etc. etc.
B - 1 = 3.5
B - 2 = 4.1
B - 3 = 8.1
etc. etc.

我知道,这要问很多,但到目前为止我已经这样做了:

import xlrd #import package

#opening workbook and reading first sheet
book = xlrd.open_workbook('trend.xls')
sheet = book.sheet_by_index(0)

#print sheet name, number of rows and columns
#print sheet.name #print sheet name
#print sheet.nrows #print number of rows
#print sheet.ncols #print number of colums

#print cellname along with value in for loop
for row_index in range(sheet.nrows):
    for col_index in range(sheet.ncols):
        print xlrd.cellname(row_index,col_index),'-',
        print sheet.cell(row_index,col_index).value

它开始打印每个单元格中的所有值,以及名称等 . 但后来我意识到它没有按照它应该做的那样做 . 而且我找不到关于如何做到这一点的正确教程 .

如果你们有任何建议,我会非常感激 . 非常感谢!

1 回答

  • 2

    试试这个:

    import xlrd
    
    book = xlrd.open_workbook('trend.xls')
    sheet = book.sheet_by_index(0)
    
    unique_combinations = {}
    
    for row_index in range(sheet.nrows):
        cell_1 = sheet.cell(row_index, 0)
        cell_2 = sheet.cell(row_index, 1)
        cell_3 = sheet.cell(row_index, 2)
        unique_combo = (cell_1.value, int(cell_2.value))
        if unique_combinations.has_key(unique_combo):
            unique_combinations[unique_combo].append(cell_3.value)
        else:
            unique_combinations[unique_combo] = [cell_3.value]
    
    for k in unique_combinations.keys():
        values = unique_combinations[k]
        average = sum(values ) / len(values )
        print '%s - %s = %s' % (k[0], k[1], average)
    

相关问题