0

過去の質問で、私は Python は初めてだと述べました。仕事で一度だけ使用しました。繰り返しになりますが、仕事のためにやらなければならない小さなプロジェクトがあります。

私はExcelファイルを読む必要があり、そのExcelファイルには3つの列(col1、col2、col3)があります。約100行あります。

col1 には A と B の 2 つの値があります。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

名前などとともに、各セル内のすべての値の出力を開始しました。しかし、実際にやるべきことをしていないことに気付きました。そして、これを行う方法に関する適切なチュートリアルが見つかりません。

何か提案があれば、よろしくお願いします。どうもありがとう!

4

1 に答える 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)
于 2013-03-12T16:09:19.920 に答える