gpt4 book ai didi

python - 使用Python计算Excel中的值

转载 作者:行者123 更新时间:2023-12-01 05:48:11 25 4
gpt4 key购买 nike

我是Python新手,我在这个问题上遇到了很多麻烦,这是我工作中必须要做的事情。

有关 Excel 文件的一些背景:有 3 列,大约 100 行。第一列 (col1) 包含 A 或 B。第二列 (col2) 包含 1 到 10 之间的任何数字。第三列 (col3) 包含任何十进制数字的值。

我希望程序做的是解析数据。 col1 和 col2 的许多重复项放在一起。例如,(A, 1) 可以位于第 1、5、20、98 行等。但 col3 将是不同的数字。因此,对于第三列中的那些不同数字,我希望它找到所有这些数字的平均值。

输出应如下所示:

A, 1 = avg 4.32
A, 2 = avg 7.23
A, 3 = avg -9.12
etc etc (until number 10)
B, 1 = avg 3.76
B, 2 = avg -8.12
B, 3 = avg 1.56
etc etc (until number 10)

它不必按完整的字母和数字顺序排列,它可以只打印出它找到的第一个组合..但到目前为止我已经在我的代码中做到了这一点,并且由于某种原因它不打印所有连击,只有 3 个。

import xlrd #import package

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

#function to hold unique combos
unique_combinations = {}

#looping through data
for row_index in range(sheet.nrows):
#declaring what group equals to what row
col1 = sheet.cell(row_index, 0)
col2 = sheet.cell(row_index, 1)
col3 = sheet.cell(row_index, 2)

unique_combo = (col1.value, col2.value)

if unique_combinations.has_key(unique_combo):
unique_combinations[unique_combo].append(col3.value)
else:
unique_combinations[unique_combo] = [col3.value]

for k in unique_combinations.keys():
l = unique_combinations[k]
average = sum(l) / len(l)
print '%s: %s Mean = %s' % (k[0], k[1], average)

本质上,它基本上是 2 个组,这 2 个组内还有另外 10 个组,这 10 个组内是属于该组的数字的平均值。

请帮忙!提前非常感谢您。

Excel 文件示例:

col1 | col2 | col3
A | 1 | 3.12
B | 9 | 4.12
B | 2 | 2.43
A | 1 | 9.54
B | 8 | 2.43
A | 2 | 1.08

所以程序要做的就是看到它遇到的第一个组合是 A, 1,它将把 3.12 存储在一个列表中,然后查看下一个组合并继续存储,直到遇到一个重复的组合是第四行。它也会存储该值。最后,输出将显示 A, 1 = avg (3.12 + 9.54/2)。此示例仅显示 A, 1 组合。但实际上,只有 2 个组(如示例),但 col2 的范围可以从 1 到 10。会有很多重复项。

最佳答案

这个建议更多的是“如何弄清楚正在发生的事情”,并且在答案中比在评论中更容易阅读。

我认为添加调试打印和异常处理是值得的。

我使用 OpenOffice 和 Python 2.7 尝试了该示例。如果在最后一个循环期间发生异常,并且如果我在测试运行中吞咽了 stderr,我可以重现您的症状。例如:python test.py 2>nul

所以我建议你尝试一下:


import xlrd
book = xlrd.open_workbook('trend.xls')
sheet = book.sheet_by_index(0)
unique_combinations = {}
for row_index in range(sheet.nrows):
col1 = sheet.cell(row_index, 0)
col2 = sheet.cell(row_index, 1)
col3 = sheet.cell(row_index, 2)

unique_combo = (col1.value, col2.value)
if unique_combinations.has_key(unique_combo):
print 'Update: %r = %r' % (unique_combo, col3.value)
unique_combinations[unique_combo].append(col3.value)
else:
print 'Add: %r = %r' % (unique_combo, col3.value)
unique_combinations[unique_combo] = [col3.value]

for k in unique_combinations.keys():
l = unique_combinations[k]
try:
average = sum(l) / len(l)
print '%s: %s Mean = %s' % (k[0], k[1], average)
except Exception, e:
print 'Ignoring entry[%r]==%r due to exception %r' % (k, l, e)

这应该可以帮助您了解我们的“奇怪行为”。

关于python - 使用Python计算Excel中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15373256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com