2012-12-06 7 views
0

xlrd 라이브러리를 사용하여 Excel 파일을 구문 분석하는 Python 스크립트를 만들고 있습니다. 내가 원하는 것은 다른 열에서 계산을하는 것입니다. if 셀에 특정 값이 들어 있습니다. 그렇지 않으면 해당 값을 건너 뜁니다. 그런 다음 출력을 사전에 저장하십시오. 여기 내가하려고 작업은 다음과 같습니다파이썬으로 Excel을 건너 뜁니다.

import xlrd 


workbook = xlrd.open_workbook('filter_data.xlsx') 
worksheet = workbook.sheet_by_name('filter_data') 

num_rows = worksheet.nrows -1 
num_cells = worksheet.ncols - 1 

first_col = 0 
scnd_col = 1 
third_col = 2 

# Read Data into double level dictionary 
celldict = dict() 
for curr_row in range(num_rows) : 

    cell0_val = int(worksheet.cell_value(curr_row+1,first_col)) 
    cell1_val = worksheet.cell_value(curr_row,scnd_col) 
    cell2_val = worksheet.cell_value(curr_row,third_col) 

    if cell1_val[:3] == 'BL1' : 
     if cell2_val=='toSkip' : 
     continue 
    elif cell1_val[:3] == 'OUT' : 
     if cell2_val == 'toSkip' : 
     continue 
    if not cell0_val in celldict : 
     celldict[cell0_val] = dict() 
# if the entry isn't in the second level dictionary then add it, with count 1 
    if not cell1_val in celldict[cell0_val] : 
     celldict[cell0_val][cell1_val] = 1 
     # Otherwise increase the count 
    else : 
     celldict[cell0_val][cell1_val] += 1 

그래서 여기에 당신이 볼 수 있듯이, 나는 각 "cell0_val"에 대한 "cell1_val"값의 수를 계산합니다. 그러나 합계를 수행하고 사전에 저장하기 전에 인접한 열의 셀에있는 "toSkip"값을 건너 뛰고 싶습니다. 저는 여기서 뭔가 잘못하고 있습니다. 해결책이 훨씬 더 간단하다고 느낍니다. 도움이 될 것입니다. 감사.

은 여기 내 시트의 예 : 그것은 당신이 cell2_val'toSkip'에 해당 할 때마다 직접 cell2_val을 계산 한 후 if cell2_val=='toSkip' : continue를 추가하는 경우는 코드를 단순화 할 수 있도록, 현재 행을 건너 뛰려면 나타납니다

cell0 cell1 cell2 
12 BL1 toSkip 
12 BL1 doNotSkip 
12 OUT3 doNotSkip 
12 OUT3 toSkip 
13 BL1 doNotSkip 
13 BL1 toSkip 
13 OUT3 doNotSkip 
+0

도움이된다면 [DataNitro] (https://datanitro.com/)를보고 싶을 것입니다. – jdotjdot

+0

작업중인 워크 시트를 더 잘 시각화 할 수 있도록 샘플 데이터를 제공하면 도움이됩니다. 특히 "toSkip"이 건너 뛰는 셀에 있는지 아니면 옆에있는 셀에 있는지 명확하지 않은 경우 데이터를 보완 할 때 도움이되지 않습니다. – jdotjdot

+0

@jdotjdot 내 질문을 편집했습니다. 감사. – salamey

답변

1

중첩 된 사전에 collections.defaultdictcollections.Counter을 사용하십시오.

는 여기 행동에 : 그것은 당신의 코드에 통합되어

다음
>>> from collections import defaultdict, Counter 
>>> d = defaultdict(Counter) 
>>> d['red']['blue'] += 1 
>>> d['green']['brown'] += 1 
>>> d['red']['blue'] += 1 
>>> pprint.pprint(d) 
{'green': Counter({'brown': 1}), 
'red': Counter({'blue': 2})} 

:

from collections import defaultdict, Counter 
import xlrd 

workbook = xlrd.open_workbook('filter_data.xlsx') 
worksheet = workbook.sheet_by_name('filter_data') 

first_col = 0 
scnd_col = 1 
third_col = 2 

celldict = defaultdict(Counter) 
for curr_row in range(1, worksheet.nrows): # start at 1 skips header row 

    cell0_val = int(worksheet.cell_value(curr_row, first_col)) 
    cell1_val = worksheet.cell_value(curr_row, scnd_col) 
    cell2_val = worksheet.cell_value(curr_row, third_col) 

    if cell2_val == 'toSkip' and cell1_val[:3] in ('BL1', 'OUT'): 
     continue 

    celldict[cell0_val][cell1_val] += 1 

또한 귀하의 경우-문에서도 결합 간단 할 curr_row의 계산을 변경했습니다.

+0

고마워요, 이렇게하면 많은 일이 단순 해지고 제가 원하는대로합니다. – salamey

0

. 당신이

입니다
celldict[cell0_val][cell1_val] = celldict[cell0_val].get(cell1_val, 0) + 1 

, 그래서 0의 기본 값을 사용하여 더 같은

# if the entry isn't in the second level dictionary then add it, with count 1 
if not cell1_val in celldict[cell0_val] : 
    celldict[cell0_val][cell1_val] = 1 
    # Otherwise increase the count 
else : 
    celldict[cell0_val][cell1_val] += 1 

는 일반적인 관용구가 있습니다 또한

, 그 cell1_valcelldict[cell0_val] 아직되어 있지 않은 경우, get()은 0을 반환합니다.

+0

고마워요, 이것도 작동합니다! – salamey

관련 문제