2015-01-17 7 views
-3

2 개의 CSV 파일이 있습니다. 도시 이름, 인구 및 습도 하나. 두 번째 도시에서는 주에 매핑됩니다. 나는 국가적인 총 인구와 평균 습도를 얻고 싶다. 누군가 도울 수 있습니까?Python을 사용한 데이터 분석

CSV 1 :

CityName,population,humidity 
Austin,1000,20 
Sanjose,2200,10 
Sacramento,500,5 

CSV 2

State,city name 
Ca,Sanjose 
Ca,Sacramento 
Texas,Austin 

이 (상태에 대한 합 인구 평균 습도)의 출력을 얻고 자하는 것이다 :

Ca,2700,7.5 
Texas,1000,20 
+3

도움이 될 수 있도록 작성한 코드가 있으십니까? – Tux

+0

팬더를 사용하고 함수처럼 Sumif를 구현했지만 두 CSV 파일 데이터를 매핑하는 방법을 모릅니다. 루프를 사용하지 않고. 어떤 방법을 찾고 나는 이것을 할 수있다. 답장을 보내 주셔서 감사합니다 – MEddy

+0

작성한 코드를 넣어서 볼 수 있습니다. 또한 루프 사용에 대한 제약이 있습니까? – Tux

답변

-1
여기 예제
def output(file1, file2): 

    f = lambda x: x.strip()  #strips newline and white space characters 

    with open(file1) as cities: 
     with open(file2) as states: 
      states_dict = {} 
      cities_dict = {} 

      for line in states: 
       line = line.split(',') 
       states_dict[f(line[0])] = f(line[1]) 
      for line in cities: 
       line = line.split(',') 
       cities_dict[f(line[0])] = (int(f(line[1])) , int(f(line[2]))) 

    for state , city in states_dict.iteritems(): 
     try: 
      print state, cities_dict[city] 
     except KeyError: 
      pass 

output(CSV1,CSV2) #these are the names of the files 

이렇게하면 원하는 출력을 얻을 수 있습니다. 디. 두 파일의 도시 이름이 대문자로 동일한 지 확인하십시오.

0

사전에 하나의 키 값이 포함되어 있기 때문에 위의 해결책이 작동하지 않습니다. 나는 포기하고 마침내 루프를 사용했다. 아래 코드도 작동합니다. 입력 한 내용도 마찬가지입니다.

csv1           
     state_name,city_name     
     CA,sacramento 
     utah,saltlake 
     CA,san jose 
     Utah,provo 
     CA,sanfrancisco 
     TX,austin 
     TX,dallas 
     OR,portland 

CSV2 
    city_name population humidity 
    sacramento 1000 1 
    saltlake 300 5 
    san jose 500 2 
     provo 100 7 
    sanfrancisco 700 3 
    austin 2000 4 
    dallas 2500 5 
    portland 300 6 

def mapping_within_dataframe(self, file1,file2,file3): 
     self.csv1 = file1 
     self.csv2 = file2 
     self.outcsv = file3 
     one_state_data = 0 
     outfile = csv.writer(open('self.outcsv', 'w'), delimiter=',') 

     state_city = read_csv(self.csv1) 
     city_data = read_csv(self.csv2) 

     all_state = list(set(state_city.state_name)) 

     for one_state in all_state: 

      one_state_cities = list(state_city.loc[state_city.state_name == one_state, "city_name"]) 
      one_state_data = 0 

      for one_city in one_state_cities: 
       one_city_data = city_data.loc[city_data.city_name == one_city, "population"].sum() 
       one_state_data = one_state_data + one_city_data 

      print one_state, one_state_data 

      outfile.writerows(whatever) 
관련 문제