【问题标题】:Read Excel Files and Only Use Specific Files读取 Excel 文件并仅使用特定文件
【发布时间】:2023-03-23 07:44:01
【问题描述】:

在我过去的问题中,我说过我是 python 新手。我只在工作中使用过一次。再说一次,我还有一个小项目要做。

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

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

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

希望输出看起来像这样:

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

它开始打印每个单元格中的所有值,以及名称等。 但后来我意识到它并没有做它应该做的事情。 而且我找不到有关如何执行此操作的适当教程。

如果你们有任何建议,我将不胜感激。非常感谢!

【问题讨论】:

    标签: python excel printing xlrd


    【解决方案1】:

    试试这个:

    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)
    

    【讨论】:

    • 我看到这只是打印出来的。有什么办法可以让它像..如果这个单元格(col1)等于一个字符串,它会开始查看col2,然后如果那个单元格值等于某个字符串,它会记录所有的值col3 对应并计算 avg??
    • 忙于编辑 - 因为您在我发布原始答案几秒钟后编辑了您的问题:-)
    • 这意味着您将一个整数传递给 len() 函数。也许您输入了 1(one) 而不是 l(L),让我们重命名列表(现在正在编辑)
    • 你是对的。 :) 非常感谢您提供的所有帮助。它并没有完成所有事情,但我希望可以从这里开始。
    • 对不起,如果我一直打扰你。但是有没有办法打印出 col2 的所有值,然后打印出 col3 的相应平均值?当我使用它时,它只打印出几个值。它看起来像这样:A - 9 = -5.07857142857 B - 3 = 1.15 B - 10 = -6.6125 但是,我知道 col2 中有更多的值,范围从 1 到 10。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 2022-06-23
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    相关资源
    最近更新 更多