2014-10-09 2 views
0

나는 강도에 대한 정보가 포함 된 36352 행의 큰 Excel 파일이 있습니다. 각 행에는 사건이 발생한 지방 자치 단체의 이름과 날짜가 들어 있습니다. 이 데이터 세트를 각 지자체의 일정표로 변환하여 일년 중 매일 얼마나 많은 강도질이 있었는지를 나타냅니다.사전 : 하나의 키에 추가 된 값도 다른 키에 추가됨

먼저 날짜가 키이고 값이 0으로 초기화 된 도난 숫자 ({day1: 0, day2: 0}) 인 캘린더 맵 (사전)을 만들었습니다.

다음으로 나는 다른 사전을 만들었습니다. 여기서 열쇠는 시정촌의 이름이고 값은 달력 사전입니다.

예컨대 :

Dictionary['New York'] = {day1: 0, day2: 0, day3: 0} 

이 초기화 잘 작동합니다. 내가했다

다음 단계는 (content_split에 기록) 행으로 내 데이터 집합 행을 통해 이동하는 것입니다, 지방 자치 단체의 이름과 키와 같은 이벤트의 날짜를했다, 값에 1을 추가 :

Dictionary[name-in-column-14-of-excel-file][day-of-event] += 1 
그때 한 지방 자치 단체의 일정 사전에 보면

for k in range(1,len(excelfile)): #for all rows in the excel file 
    # datetime.datetime(year,month,day) 
    d = datetime.datetime(int(content_split[k][9]),int(content_split[k][8]),int(content_split[k][7])) 
    # Dictionary[name-of-municipality][timestamp-in-utc] += 1 
    Municipality_dict[content_split[k][14]][calendar.timegm(d.timetuple())] += 1 

, 나는 매우 높은 숫자 (1 개 도시 1 일 동안 176 개 도난) 및 다른 지방 자치 단체의 일정지도를 얻을 :

나는 루프로 쓴 동일합니다. 따라서 내 시정촌 열쇠가 작동하지 않는 것 같지만 단서가 없습니다.

내가 뭘 잘못하고 있는지 아는 사람이 있습니까? 나는 사전을 만든 방법에 대한

편집 : 당신은 키가 지방 자치 단체의 이름을있는 두 번째 사전을 만들 때, 각각의 키가 같은 사전에 대한 참조로 할당 받고처럼

# Open map containing the days 
with open('days.csv') as f1: 
    days_temp = f1.readlines() 

alldays = [] 

# Get dd;mm;yy format to [dd, mm, yy] format 
for day in days_temp: 
    alldays.append(day.strip().split(';')) 

Timestamp = {} 

# Convert days into UTC codes 
for i in range(len(alldays)): 
d = datetime.datetime(int(alldays[i][2]),int(alldays[i][1]),int(alldays[i][0])) 

# dictionary[UTC-time-code] = 0 (no burglaries occurred) 
Timestamp[calendar.timegm(d.timetuple())] = 0 

# Open file with names of municipalities 
with open('file2.csv') as f2: 
    municipalities_temp = f2.readlines() 

municipalities_dict = {} 

# dictionary[name-of-municipality] = calendar 
for instance in municipalities_temp: 
    municipalities_dict[instance.strip()] = Timestamp 
+1

* 사전을 어떻게 만들었습니까? 참조를 공유하고 별도의 객체가 아닌 * * 사전 하나만 가지고 있습니다. –

+2

'd = { 'day1': 0, ...}; M_D [ 'New York'] = d; M_D [ 'Boston'] = d; ... ', 당신은 당신이 얻고있는 결과를 보게 될 것입니다. – chepner

+0

원래 게시물을 편집했습니다. 처음에는 '공유 참조'부분을 이해하지 못했지만 지금은 ErlVolton의 회신으로 귀하의 뜻을 이해합니다. :) – Jolien

답변

0

소리가 난다. 다음 예제를 참조하십시오 :

>>> test = {"x":"y"} 
>>> test2 = test 
>>> test["x"] = "foo" 
>>> test2 
{'x': 'foo'} 
>>> 

주 TEST2 [ "x"는] TEST2 테스트에 대한 참조이기 때문에 테스트가 변경 될 때 foo는 변경 있음을, 그리고 그것을 자신의 사전입니다. 해결책?

import copy 

template_dict = {day1: 0, day2: 0, day3: 0} 
Dictionary['New York'] = copy.deepcopy(template_dict) 
+0

굉장! 그게 효과가 있었어! – Jolien

+0

@Jolien. 또한, 복사하는 대신에'template_dict = lambda : {day1 : 0, day2 : 0, day3 : 0}'을 사용할 수 있고, Dictionary [ 'New York'] = template_dict()'로 사용할 수있다. 'day1', 'day2'및 'day3') –

관련 문제