2016-07-13 4 views
0

그래서 한 열에는 날짜 목록이 있고 다른 열에는 값 목록이 있습니다.Python Excel의 두 열의 목록

2/8/13 474 
2/7/13 463.25 
2/6/13 456.47 
2/5/13 444.05 
2/4/13 453.91 
2/1/13 459.11 
1/31/13 456.98 
1/30/13 457 
1/29/13 458.5 
1/28/13 437.83 
1/25/13 451.69 
1/24/13 460 
1/23/13 508.81 
1/22/13 504.56 
1/18/13 498.52 
1/17/13 510.31 

첫 번째 열의 날짜를 컴파일하고 해당 월의 평균값을 출력하는 방법을 찾아야합니다.

출력은 월 : year average_value_for_month와 같아야합니다. 예를 들어, 첫 번째 두 개의 출력은

02:2013 458.46 

01:2013 500.08 

^이 2013 년 2 월의 달 월에 대한 평균 값이 지금 458.46,500.08

내 코드라고 말한다처럼

보일 것입니다 ,

def averageData(list_of_tuples): 
    #print(list_of_tuples) #prints out the list obtained from getDataList 
    sep_list = [] 
    for i in range(0,len(list_of_tuples)): 
     split_list = list_of_tuples[i].split() 
     sep_list.append(split_list) 
     #print(sep_list[i]) #prints out list with index [i][0] being the date and index [i][1] being the column value 
    new_list = [] 
    for i in range(0,len(sep_list)): 
     sep_list[i][0] = sep_list[i][0].split('-') #splits dates in year, month, day 
     #print(sep_list[i][0]) 
     print(sep_list[i][0]) 
    for i in range(0,len(sep_list)): 
     if sep_list[i][0][0] == sep_list[i+1][0][0] and sep_list[i][0][1] == sep_list[i+1][0][1]: 
      new_date = sep_list[i][0][1]+':'+sep_list[i][0][0] 
     new_list.append(new_date) 
     #print(new_list[i]) 

원래 목록

['2013-02-08 474.00'] 
같은 형식입니다 16,

루프에 대한 나의 첫 번째 목록은 다음

['2013-02-08', '474.00'] 

될 루프의 두 번째

[['2013', '02', '08'], '474.00'] 

내가 여기에서 이동하는 위치에 붙어에 목록을 전환합니다. 도와주세요.

+0

피벗 테이블을 사용해보세요! http://stackoverflow.com/questions/15570099/pandas-pivot-tables-row-subtotals –

답변

0

.split 및 [:] 구분 기호와 같은 목록 메서드를 결합하여 루프 및 목록을 줄이고 더 좋은 개요를 유지할 수 있습니다. "튜플"라는 주어진 튜플의 예 :이 같은 조직하여 변수를 유지하는 경우

datelist=tuple.split(" ")[0].split("/") 
    month=datelist[0] 
    year=datelist[2] 
    value=tuple.split(" ")[1] 

, 나는 = 당신은 자신에 의해 나머지를 알아낼 수 있다고 생각)

0

여기 내 솔루션입니다. 도움이 되었기를 바랍니다 :

from datetime import datetime 

def averageData(list_of_tuples): 
    dic = {}  
    for i in list_of_tuples: 
     i = list(map(str,i.strip().split(' '))) 
     dt = datetime.strptime(i[0] , '%Y-%m-%d') 
     if (dt.month,dt.year) in dic: 
      dic[(dt.month,dt.year)].append(float(i[1])) 
     else: 
      dic[(dt.month,dt.year)] = [float(i[1])] 

    for i in dic.items(): 
     #print(i) 
     print (str(i[0][0])+':'+str(i[0][1])+' '+str(round(sum(i[1])/len(i[1]),2))) 

tuples = ['2013-02-08 474','2013-02-07 463.25','2013-02-06 456.47', 
'2013-02-05 444.05', 
'2013-02-04 453.91', 
'2013-02-01 459.11', 
'2013-01-31 456.98', 
'2013-01-30 457', 
'2013-01-29 458.5', 
'2013-01-28 437.83', 
'2013-01-25 451.69', 
'2013-01-24 460', 
'2013-01-23 508.81', 
'2013-01-22 504.56', 
'2013-01-18 498.52', 
'2013-01-17 510.31'] 

averageData(tuples) 
관련 문제