Beispiel #1
0
class CrimeMap:
    def __init__(self):
        self.dr = DataReader()

    def hook(self):
        self.create_seoul_crime_map()

    def create_seoul_crime_map(self):
        self.dr.context = './saved_data/'
        self.dr.fname = 'police_norm.csv'
        police_norm = self.dr.csv_to_dframe()
        # print(pn)
        self.dr.context = './data/'
        self.dr.fname = 'geo_simple.json'
        seoul_geo = self.dr.json_load()
        self.dr.context = './data/'
        self.dr.fname = 'crime_in_seoul.csv'
        crime = self.dr.csv_to_dframe()

        station_names = []
        for name in crime['관서명']:
            station_names.append('서울' + str(name[:-1] + '경찰서'))
        station_addrs = []
        station_lats = []  # 위도
        station_lngs = []  # 경도
        gmaps = self.dr.create_gmaps()
        for name in station_names:
            t = gmaps.geocode(name, language='ko')
            station_addrs.append(t[0].get('formatted_address'))
            t_loc = t[0].get('geometry')
            station_lats.append(t_loc['location']['lat'])
            station_lngs.append(t_loc['location']['lng'])
            # print(name + '---------> ' + t[0].get('formatted_address'))
        # 기존 코드
        self.dr.context = './data/'
        self.dr.fname = 'police_position.csv'
        police_pos = self.dr.csv_to_dframe()
        police_pos['lat'] = station_lats
        police_pos['lng'] = station_lngs
        # print(police_pos)
        col = ['살인 검거', '강도 검거', '강간 검거', '절도 검거', '폭력 검거']
        tmp = police_pos[col] / police_pos[col].max()
        police_pos['검거'] = np.sum(tmp, axis=1)
        self.dr.fname = 'geo_simple.json'
        m = folium.Map(location=[37.5502, 126.982],
                       zoom_start=12,
                       title='Stamen Toner')
        m.choropleth(geo_data=seoul_geo,
                     name='choropleth',
                     data=tuple(zip(police_norm['구별'], police_norm['범죄'])),
                     key_on='feature.id',
                     fill_color='PuRd',
                     fill_opacity=0.7,
                     line_opacity=0.2,
                     legend_name='CRIME RATE (%)')
        for i in police_pos.index:
            folium.CircleMarker([police_pos['lat'][i], police_pos['lng'][i]],
                                radius=police_pos['검거'][i] * 10,
                                fill_color='#0a0a32').add_to(m)
        m.save('./saved_data/Seoul_Crime_Map.html')
class CrimeMap:
    def __init__(self):
        self.dr = DataReader()

    def hook(self):
        self.crate_seoul_crime_map()

    def crate_seoul_crime_map(self):
        self.dr.context = './saved_data/'
        self.dr.fname = 'police_norm.csv'
        pn = self.dr.csv_to_dframe()
        # print("===============")
        # print(pn)

        self.dr.context = './data'
        self.dr.fname = '/geo_simple.json'
        seoul_geo = self.dr.json_load()
        m = folium.Map(location=[37.5502, 126.982],
                       zoom_start=12,
                       title='Stamen Toner')
        m.choropleth(
            geo_data=seoul_geo,
            name='choropleth',
            data=tuple(zip(pn['구별'], pn['범죄'])),
            # columns=['State', 'Unemployment'],
            key_on='feature.id',
            fill_color='PuRd',
            fill_opacity=0.7,
            line_opacity=0.2,
            legend_name='Crime Rate (%)')
        m.save('./saved_data/Seoul_Crime.html')
Beispiel #3
0
class CrimeModel:
    def __init__(self):
        self.dr = DataReader()

    def hook_process(self):
        print('-------------1. CCTV 파일로 DF 생성 ------------')
        self.get_crime()

    def get_crime(self):
        self.dr.context = './data/'
        self.dr.fname = 'crime_in_seoul.csv'
        crime = self.dr.csv_to_dframe()

        station_names = []
        for name in crime['관서명']:
            station_names.append('서울' + str(name[:-1] + '경찰서'))
        
        station_addrs = []
        station_lats = [] # 위도
        station_lngs = [] # 경도

        gmaps = self.dr.create_gmap()
        for name in station_names:
            t = gmaps.geocode(name, language='ko')
            station_addrs.append(t[0].get('formatted_address'))
            t_loc = t[0].get('geometry')
            station_lats.append(t_loc['location']['lat'])
            station_lngs.append(t_loc['location']['lng'])
            print(name + '---------->' + t[0].get('formatted_address'))
Beispiel #4
0
class PoliceNormModel:
    def __init__(self):
        self.dr = DataReader()

    def hook_process(self):
        print('----------------1. cctv 파일 DF 생성--------------------')
        self.create_crime_rate()

    def create_crime_rate(self):
        self.dr.context = './saved_data/'
        self.dr.fname = 'crime_police.csv'
        police_crime = self.dr.csv_to_dframe()
        police = pd.pivot_table(police_crime, index='구별', aggfunc=np.sum)
        print(police.columns)
        police['살인검거율'] = (police['살인 검거'] / police['살인 발생']) * 100
        police['강도검거율'] = (police['강도 검거'] / police['강도 발생']) * 100
        police['강간검거율'] = (police['강간 검거'] / police['강간 발생']) * 100
        police['절도검거율'] = (police['절도 검거'] / police['절도 발생']) * 100
        police['폭력검거율'] = (police['폭력 검거'] / police['폭력 발생']) * 100
        police.drop(columns={'살인 검거','강도 검거','강간 검거','절도 검거','폭력 검거'}, axis=1)
        crime_rate_columns = ['살인검거율','강도검거율','강간검거율','절도검거율','폭력검거율']
        for i in crime_rate_columns:
            police.loc[police[i] > 100, 1] = 100 #비율이 100%가 넘는 경우 100으로 치환
        police.rename(columns = {
            '살인 발생' : '살인',
            '강도 발생' : '강도',
            '강간 발생' : '강간',
            '절도 발생' : '절도',
            '폭력 발생' : '폭력'
        }, inplace=True)

        crime_columns = ['살인', '강도', '강간', '절도', '폭력']

        x = police[crime_rate_columns].values

        min_max_scalar = preprocessing.MinMaxScaler()
        #차원이 올라가면 collection이 객체로 전환됨
        #return되는 값의 차원이 올라가면 scalar로 전환
        #결국, 학습결과로 최종적으로 산출되는 것은 scalar(단위값). collection이 아님
        # 스케일링은 선형변환을 적응하여 전체 자료의 분포를 평균 0, 분산 1이 되도록 만드는 과정

        x_scaled = min_max_scalar.fit_transform(x.astype(float))

        # 정규화(normalization)
        # 많은 양의 데이터를 처리함에 있어 여러 이유로 정규화,
        # 즉 데이터의 범위를 일치시키거나 분포를 유사하게 만들어주는 등의 작업
        # 평균값 정규화, 중간값 정규화.....

        police_norm = pd.DataFrame(x_scaled,
                                   columns=crime_columns,
                                   index=police.index)
        police_norm[crime_rate_columns] = police[crime_rate_columns]
        self.dr.context = './saved_data'
        self.dr.fname = '/cctv_pop.csv'
        cctv_pop = pd.read_csv(self.dr.new_file(), encoding='UTF-8', sep=',', index_col='구별')
        police_norm['범죄'] = np.sum(police_norm[crime_rate_columns], axis=1)
        police_norm['검거'] = np.sum(police_norm[crime_columns], axis=1)
        print(police_norm.columns)
        police_norm.to_csv('./saved_data/police_norm.csv')
Beispiel #5
0
class CCTVModel:
    def __init__(self):
        self.dr = DataReader()

    def hook_process(self):
        print('----------------1.cctv 파일로 DF 생성---------------')
        self.get_cctv()

    def get_cctv(self):
        self.dr.context = './data/'
        self.dr.fname = 'cctv_in_seoul.csv'
        cctv = self.dr.csv_to_dframe()
        #print(cctv.columns)#Index(['기관명', '소계', '2013년도 이전', '2014년', '2015년', '2016년'], dtype='object')
        self.dr.fname = 'population_in_seoul.xls'
        pop = self.dr.xls_to_dframe(2, 'B,D,G,J,N')
        #print(pop.columns)#Index(['자치구', '계', '계.1', '계.2', '65세이상고령자'], dtype='object')
        cctv.rename(columns={cctv.columns[0]: '구별'}, inplace=True)
        pop.rename(columns={
            pop.columns[0]: '구별',
            pop.columns[1]: '인구수',
            pop.columns[2]: '한국인',
            pop.columns[3]: '외국인',
            pop.columns[4]: '고령자'
        },
                   inplace=True)

        #pop.drop([0],True)
        #print(pop['구별'].isnull())
        pop.drop([26], inplace=True)  #null 인 데이타 행 삭제하기
        #컬럼추가
        pop['외국인비율'] = pop['외국인'] / pop['인구수'] * 100
        pop['고령자비율'] = pop['고령자'] / pop['인구수'] * 100

        cctv.drop(['2013년도 이전', '2014년', '2015년', '2016년'], 1, inplace=True)
        cctv_pop = pd.merge(cctv, pop, on='구별')  #구별 컬럼명으로 cctv와 pop합치기
        #상관관계 보기
        cor1 = np.corrcoef(cctv_pop['고령자비율'], cctv_pop['소계'])
        cor2 = np.corrcoef(cctv_pop['외국인비율'], cctv_pop['소계'])

        print('고령자 비율과 CCTV위 상관계수 {}\n외국인 비율과 CCTV위 상관계수 {}'.format(
            cor1, cor2))
        '''
        상관관계가 없는 경우  feature를 제거하자
        
        r이 -1.0과 -0.7 사이이면, 강한 음적 선형관계,
        r이 -0.7과 -0.3 사이이면, 뚜렷한 음적 선형관계,
        r이 -0.3과 -0.1 사이이면, 약한 음적 선형관계,
        r이 -0.1과 +0.1 사이이면, 거의 무시될 수 있는 선형관계,
        r이 +0.1과 +0.3 사이이면, 약한 양적 선형관계,
        r이 +0.3과 +0.7 사이이면, 뚜렷한 양적 선형관계,
         r이 +0.7과 +1.0 사이이면, 강한 양적 선형관계
        고령자비율 과 CCTV 상관계수 [[ 1.         -0.28078554] 약한 음적 선형관계
                                   [-0.28078554  1.        ]]
        외국인비율 과 CCTV 상관계수 [[ 1.         -0.13607433] 거의 무시될 수 있는
                                   [-0.13607433  1.        ]]
        
        '''
        cctv_pop.to_csv('./saved_data/cctv_pop.csv')
Beispiel #6
0
class CrimeMap:
    def __init__(self):
        self.dr = DataReader()
    def hook(self):
        self.create_seoul_crime_map()

    def create_seoul_crime_map(self):
        self.dr.context='./saved_data/'
        self.dr.fname = 'police_norm.csv'
        pn = self.dr.csv_to_dframe()
        print(pn)
Beispiel #7
0
class CCTVModel:
    def __init__(self):
        self.dr = DataReader()

    def hook_process(self):
        print('----------------1. cctv 파일 DF 생성--------------------')
        self.get_cctv()

        #cctv정보파일 읽어오기
    def get_cctv(self):
        self.dr.context = './data/'
        self.dr.fname = 'cctv_in_seoul.csv'
        cctv = self.dr.csv_to_dframe()
        # 인덱스 확인을 위한 출력문 print(cctv.columns)
        print(cctv.columns)
        # print(cctv) -> 제대로 df로 불러들였는지 확인용
        self.dr.fname = 'pop_in_seoul.xls'
        pop = self.dr.xls_to_dframe(2, 'B,D,G,J,N')
        # B, D, G, J, N 에 있는 것만 불러오기
        # print(pop) -> 제대로 df로 불러들였는지 확인용
        # 인덱스 확인을 위한 출력문 print(pop.columns)
        print(pop.columns)
        cctv.rename(columns={cctv.columns[0]: '구별'}, inplace=True)
        #inplace -> 원본을 바꾸라는 것
        pop.rename(columns={
            pop.columns[0]: '구별',
            pop.columns[1]: '인구수',
            pop.columns[2]: '한국인',
            pop.columns[3]: '외국인',
            pop.columns[4]: '고령자'
        },
                   inplace=True)
        #  pop.drop([0], True)  #1행 삭제
        #        print(pop['구별'].isnull()) #null값 있는지 확인 -> 26번째에서 True 라고 나옴. 26번째가 null값이라는 뜻 -> 삭제필요
        pop.drop([26], inplace=True)  # 27행 삭제
        pop['외국인비율'] = pop['외국인'] / pop['인구수'] * 100
        pop['고령자비율'] = pop['고령자'] / pop['인구수'] * 100

        cctv.drop(['2013년도 이전', '2014년', '2015년', '2016년'], 1,
                  inplace=True)  #연도별정보를 삭제하고 현재자료만 사용
        cctv_pop = pd.merge(cctv, pop,
                            on='구별')  #cctv와 pop이라는 df를 [구별]이라는 컬럼명에 맞게 병합
        cor1 = np.corrcoef(cctv_pop['고령자비율'], cctv_pop['소계'])
        cor2 = np.corrcoef(cctv_pop['외국인비율'], cctv_pop['소계'])

        print('고령자비율과 cctv의 상관계수 {}  \n'
              '외국인비율과 cctv의 상관계수 {}'.format(cor1, cor2))

        # 추출한 데이터를 별도의 디렉토리에 저장
        cctv_pop.to_csv('./saved_data/cctv_pop.csv')
Beispiel #8
0
class CrimeModel:
    def __init__(self):
        self.dr = DataReader()

    def hook_process(self):
        print('--------------------1. CCTV 파일로 DF 생성--------------------')
        self.get_crime()

    def get_crime(self):
        self.dr.context = './data/'
        self.dr.fname = 'crime_in_seoul.csv'
        crime = self.dr.csv_to_dframe()
        print(crime)
        station_names = []
        for name in crime['관서명']:
            station_names.append('서울' + str(name[:-1]) + '경찰서')

        station_addrs = []
        station_lats = []  # 위도
        station_lngs = []  # 경도
        gmaps = self.dr.create_gmaps()

        for name in station_names:
            t = gmaps.geocode(name, language='ko')
            station_addrs.append(t[0].get('formatted_address'))
            t_loc = t[0].get('geometry')
            station_lats.append(t_loc['location']['lat'])
            station_lngs.append(t_loc['location']['lng'])
            print(name + '----------> ' + t[0].get('formatted_address'))

        gu_names = []
        for name in station_addrs:
            t = name.split()
            gu_name = [gu for gu in t if gu[-1] == '구'][0]
            gu_names.append(gu_name)

        crime['구별'] = gu_names

        # 구와 경찰서 위치가 다른 경우 수작업

        crime.loc[crime['관서명'] == '혜화서', ['구별']] == '종로구'
        crime.loc[crime['관서명'] == '서부서', ['구별']] == '은평구'
        crime.loc[crime['관서명'] == '강서서', ['구별']] == '양천구'
        crime.loc[crime['관서명'] == '종암서', ['구별']] == '성북구'
        crime.loc[crime['관서명'] == '방배서', ['구별']] == '서초구'
        crime.loc[crime['관서명'] == '수서서', ['구별']] == '강남구'

        print(crime)

        crime.to_csv('./saved_data/crime_police.csv')
Beispiel #9
0
class CCTVModel:
    def __init__(self):
        self.dr = DataReader()

    def hook_process(self):
        print('--------1.CCTV 파일로 DF 생성 --------------')
        self.get_cctv()

    def get_cctv(self):
        self.dr.context = './data/'
        self.dr.fname = 'cctv_in_seoul.csv'
        cctv = self.dr.csv_to_dframe()
        self.dr.fname = 'population_in_seoul.xls'
        pop = self.dr.xls_to_dframe(2, 'B,D,G,J,N')

        print(cctv.columns)
Beispiel #10
0
class CCTVModel:
    def __init__(self):
        self.dr = DataReader()

    def hook_process(self):
        print('------------------ 1. CCTV 파일로 DF 생성 -------------------')
        self.get_cctv()

    def get_cctv(self):
        self.dr.context = './data/'

        self.dr.fname = 'cctv_in_seoul.csv'
        cctv = self.dr.csv_to_dframe()

        self.dr.fname = 'pop_in_seoul.xls'
        pop = self.dr.xls_to_dframe(2, 'B, D, G, J, N' )

        cctv.rename(columns={cctv.columns[0] : '구별'}, inplace=True)
        pop.rename(columns={
            pop.columns[0]: '구별',
            pop.columns[1]: '인구수',
            pop.columns[2]: '한국인',
            pop.columns[3]: '외국인',
            pop.columns[4]: '고령인'
        }, inplace=True)

        #pop.drop([0], True)
        # null값 여부 확인
        #print(pop['구별'].isnull()) 
        pop.drop([26], inplace=True)

        pop['외국인비율'] = pop['외국인'] / pop['인구수'] * 100
        pop['고령자비율'] = pop['고령인'] / pop['인구수'] * 100

        cctv.drop(['2013년도 이전', '2014년', '2015년', '2016년'], 1, inplace=True)
        cctv_pop = pd.merge(cctv, pop, on='구별')

        cor1 = np.corrcoef(cctv_pop['고령자비율'], cctv_pop['소계'])
        cor2 = np.corrcoef(cctv_pop['외국인비율'], cctv_pop['소계'])

        print(f'고령자비율과 CCTV의 상관계수 {cor1} \n 외국인비율과 CCTV의 상관계수 {cor2}')

        cctv_pop.to_csv('./saved_data/cctv_pop.csv')
        '''
class CCTVModel:
    def __init__(self):
        self.dr = DataReader()

    def hook_process(self):
        print('---------- 1. cctv 파일 df 생성 ----------')
        self.get_cctv()

    def get_cctv(self):
        self.dr.context = './data/'
        self.dr.fname = 'cctv_in_Seoul.csv'
        cctv = self.dr.csv_to_dframe()
        #print(cctv.columns)

        self.dr.fname = 'pop_in_seoul.xls'
        pop = self.dr.xls_to_dframe(2, 'B,D,G,J,N') #엑셀에서 해당 컬럼만 가져오겠다
        #print(pop.columns)

        cctv.rename(columns={cctv.columns[0]: '구별'}, inplace=True)
        pop.rename(columns={
            pop.columns[0]: '구별',
            pop.columns[1]: '인구수',
            pop.columns[2]: '한국인',
            pop.columns[3]: '외국인',
            pop.columns[4]: '고령자',
        }, inplace=True)
        #pop.drop([0], True)
        print(pop['구별'].isnull())
        pop.drop([26], inplace=True)
        pop['외국인비율'] = pop['외국인'] / pop['인구수'] * 100
        pop['고령자비율'] = pop['고령자'] / pop['인구수'] * 100

        cctv.drop(['2013년도 이전', '2014년', '2015년', '2016년'], 1, inplace=True)
        cctv_pop = pd.merge(cctv, pop, on='구별') #합쳐진 결과값

        cor1 = np.corrcoef(cctv_pop['고령자비율'], cctv_pop['소계'])
        cor2 = np.corrcoef(cctv_pop['외국인비율'], cctv_pop['소계'])
        print('고령자비율과 CCTV의 상관계수 {} \n'
              '외국인비율과 CCTV의 상관계수 {} '.format(cor1,cor2))

        cctv_pop.to_csv('./saved_data/cctv_pop.csv')


        """
class CCTVModel:
    def __init__(self):
        self.dr = DataReader()
    def hook_process(self):
        print('-'*12,'1. CCTV 파일로 DF 생성','-'*12)
        self.get_cctv()

    def get_cctv(self):
        self.dr.context = './data/'
        self.dr.fname = 'cctv_in_seoul.csv'
        cctv = self.dr.csv_to_dframe()
        print('dr의 type은 ->',type(self.dr))
        print('cctv_columns ->',cctv.columns)
        self.dr.fname='pop_in_seoul.xls'
        pop = self.dr.xls_to_dframe(2,'B,D,G,J,N')
        print('pop_columns ->',pop.columns)
        cctv.rename(columns={cctv.columns[0]: '구별'}, inplace = True)
        print('cctv의 type은 ->',type(cctv))
        pop.rename(columns={
            pop.columns[0]:'구별',
            pop.columns[1]:'인구수',
            pop.columns[2]:'한국인',
            pop.columns[3]:'외국인',
            pop.columns[4]:'고령인',
        },inplace=True)
        # pop.drop([0],True)
        # print(pop['구별'].isnull())# null값 확인하는 방법
        pop.drop([26],inplace=True)
        pop['외국인비율'] = pop['외국인'] / pop['인구수'] * 100
        pop['고령인비율'] = pop['고령인']/pop['인구수']*100

        cctv.drop(['2013년도 이전','2014년', '2015년', '2016년'], 1, inplace = True)
        cctv_pop = pd.merge(cctv,pop,on='구별')
        cor1 = np.corrcoef(cctv_pop['고령인비율'],cctv_pop['소계'])
        cor2 = np.corrcoef(cctv_pop['외국인비율'],cctv_pop['소계'])

        cctv_pop.to_csv('./saved_data/cctv_pop.csv')

        print('고령자비율 cctv의 상관계수 {0}\n'
              +'외국인비율과 cctv의 상관계수 {1}'.format(cor1,cor2))
        '''
class PoliceNmlModel:
    def __init__(self):
        self.dr = DataReader()

    def hook(self):
        print('-' * 12, '1, 생성', '-' * 12)
        self.create_crime_rate()

    def create_crime_rate(self):
        self.dr.context = './saved_data/'
        self.dr.fname = './crime_police.csv'
        police_crime = self.dr.csv_to_dframe()
        police = pd.pivot_table(police_crime, index='구별', aggfunc=np.sum)
        # print(police.columns)
        police['성인검거율'] = (police['살인 검거'] / police['살인 발생']) * 100
        police['강도검거율'] = (police['강도 검거'] / police['강도 발생']) * 100
        police['강간검거율'] = (police['강간 검거'] / police['강간 발생']) * 100
        police['절도검거율'] = (police['절도 검거'] / police['절도 발생']) * 100
        police['폭력검거율'] = (police['폭력 검거'] / police['폭력 발생']) * 100
        police.drop(columns={'살인 검거', '강도 검거', '강간 검거', '절도 검거', '폭력 검거'},
                    axis=1)
        crime_rate_columns = ['성인검거율', '강도검거율', '강간검거율', '절도검거율', '폭력검거율']
        for i in crime_rate_columns:
            police.loc[police[i] > 100,
                       1] = 100  # 데이터값의 기간 오류로 100이 넘으면 100으로 계산
        police.rename(columns={
            '살인 발생': '살인',
            '강도 발생': '강도',
            '강간 발생': '강간',
            '절도 발생': '절도',
            '폭력 발생': '폭력'
        },
                      inplace=True)
        crime_columns = ['살인', '강도', '강간', '절도', '폭력']

        x = police[crime_rate_columns].values

        min_max_scalar = preprocessing.MinMaxScaler()

        x_scaled = min_max_scalar.fit_transform(x.astype(float))
        # normalizaion
        # 분포를 유사하게
        # 평균값 정규화, 중간값 정규화 .. etc

        police_norm = pd.DataFrame(
            x_scaled,
            columns=crime_columns,
            index=police.index,
        )
        police_norm[crime_rate_columns] = police[crime_rate_columns]
        self.dr.context = './saved_data'
        self.dr.fname = '/cctv_pop.csv'
        cctv_pop = pd.read_csv(self.dr.new_file(),
                               encoding='utf-8',
                               sep=',',
                               index_col='구별')
        police_norm['범죄'] = np.sum(police_norm[crime_rate_columns], axis=1)
        police_norm['검거'] = np.sum(police_norm[crime_columns], axis=1)
        print(police_norm.columns)
        police_norm.to_csv('./saved_data/police_norm.csv',
                           sep=',',
                           encoding='utf-8')
Beispiel #14
0
class PoliceNormModel:
    def __init__(self):
        self.dr = DataReader()

    def hook_process(self):
        print('----------------1.crime 파일로 DF 생성---------------')
        self.create_crime_rate()

    def create_crime_rate(self):
        self.dr.context = './saved_data/'
        self.dr.fname = 'crime_police.csv'
        police_crime = self.dr.csv_to_dframe()
        police = pd.pivot_table(police_crime, index='구별', aggfunc=np.sum)
        print(police.columns)
        police['살인검거율'] = (police['살인 검거'] / police['살인 발생']) * 100
        police['강도검거율'] = (police['강도 검거'] / police['강도 발생']) * 100
        police['강간검거율'] = (police['강간 검거'] / police['강간 발생']) * 100
        police['절도검거율'] = (police['절도 검거'] / police['절도 발생']) * 100
        police['폭력검거율'] = (police['폭력 검거'] / police['폭력 발생']) * 100
        police.drop(columns={'강간 검거', '강도 검거', '살인 검거', '절도 검거', '폭력 검거'},
                    axis=1)
        crime_rate_columns = ['살인검거율', '강도검거율', '강간검거율', '절도검거율', '폭력검거율']
        for i in crime_rate_columns:
            police.loc[police[i] > 100,
                       1] = 100  # 데이타 값에 오류로 100이 넘으면 100으로 계산

        police.rename(columns={
            '살인 발생': '살인',
            '강도 발생': '강도',
            '강간 발생': '강간',
            '절도 발생': '절도',
            '폭력 발생': '폭력'
        },
                      inplace=True)

        crime_columns = ['살인', '강도', '강간', '절도', '폭력']

        x = police[crime_rate_columns].values

        min_max_scalar = preprocessing.MinMaxScaler()
        '''
        스케일링은 선형변환을 적응하여 전체 자료의 분포를 평균 0 ,분산 1이 되도록 만드는 과정
        
        '''
        x_scaled = min_max_scalar.fit_transform(x.astype(float))
        '''
        정규화
        많은 양의 데이타를 처리함에 있어 여러 이유로 정규화, 즉 데이타의 범위를 일치시키거나 분포를 유사하게 만들어주는 등의 작업
        평균값 정규화,증간값 정규화
        
        '''
        police_norm = pd.DataFrame(x_scaled,
                                   columns=crime_columns,
                                   index=police.index)
        police_norm[crime_rate_columns] = police[crime_rate_columns]
        self.dr.context = './saved_data/'
        self.dr.fname = 'cctv_pop.csv'
        cctv_pop = pd.read_csv(self.dr.new_file(),
                               encoding='UTF-8',
                               sep=',',
                               index_col='구별')
        police_norm['범죄'] = np.sum(police_norm[crime_rate_columns], axis=1)
        police_norm['검거'] = np.sum(police_norm[crime_columns], axis=1)

        print(police_norm.columns)

        police_norm.to_csv('./saved_data/police_norm.csv',
                           sep=',',
                           encoding='UTF-8')
Beispiel #15
0
class CrimeMap:
    def __init__(self):
        self.dr = DataReader()

    def hook(self):
        self.create_seoul_crime_map()

    def create_seoul_crime_map(self):
        self.dr.context = './saved_data/'
        self.dr.fname = 'police_norm.csv'
        police_norm = self.dr.csv_to_dframe()
        #  print(pn) #dataframe으로 제대로 불러들였는지 확인하기 위함
        self.dr.context = './data/'
        self.dr.fname = 'geo_simple.json'
        seoul_geo = self.dr.json_load()
        #폴리움 코딩은 템플릿화되어있으므로 가져와서 붙이고 데이터만 한국지도에 맞게 수정하면 됨

        self.dr.context = './data/'
        self.dr.fname = 'crime_in_seoul.csv'
        crime = self.dr.csv_to_dframe()

        station_names = []
        for name in crime['관서명']:
            station_names.append('서울' + str(name[:-1] + '경찰서'))
        station_addrs = []
        station_lats = []  #위도
        station_lngs = []  #경도
        gmaps = self.dr.create_gmaps()
        for name in station_names:
            t = gmaps.geocode(name, language='ko')
            station_addrs.append(t[0].get('formatted_address'))
            t_loc = t[0].get('geometry')
            station_lats.append(
                t_loc['location']['lat']
            )  #formatted_address, lat, lng, location 구글맵 내부에 기재되어있는 정보들이므로 그대로 사용해야함
            station_lngs.append(t_loc['location']['lng'])

    #        print(name + '--------> '+t[0].get('formatted_address')) # 구글키가 작동하는지 확인

    # 기존 코드
        self.dr.context = './data/'
        self.dr.fname = 'police_position.csv'
        police_pos = self.dr.csv_to_dframe()
        police_pos['lat'] = station_lats
        police_pos['lng'] = station_lngs
        #     print(police_pos) # 제대로 불러읽어들였는지 확인
        col = ['살인 검거', '강도 검거', '강간 검거', '절도 검거', '폭력 검거']
        tmp = police_pos[col] / police_pos[col].max
        police_pos['검거'] = np.sum(tmp, axis=1)
        self.dr.fname = 'geo_simple.json'

        m = folium.Map(location=[37.5502, 126.982],
                       zoom_start=12,
                       title='stamen Toner')  # 한국 위도, 경도 설정 및 지도 스타일 설정
        m.choropleth(
            geo_data=seoul_geo,
            name='choropleth',
            # json에서의 id와 police_norm에 있는 스키마(변수명, 컬럼)의 내용 값을 일치시켜야 하므로 pn안에서 [구별] [범죄]를 체크해야함
            # 폴리움 데이터에서 state, unemployment를 컬럼으로 가지도록 한 것과 같은 패턴
            data=tuple(zip(police_norm['구별'], police_norm['범죄'])),
            key_on='feature.id',
            fill_color='PuRd',
            fill_opacity=0.7,
            line_opacity=0.2,
            legend_name='Crime Rate (%)')
        # 괄호안의 파라메터들에 관해 파고들어갈 필요까지는 없음

        # 기존 지도에 검거율 추가
        for i in police_pos.index:
            folium.CircleMarker([police_pos['lat'][i], police_pos['lng'][i]],
                                radius=police_pos['검거'][i] * 10,
                                fill_color='#0a0a32').add_to(m)

        m.save('./saved_data/Seoul_Crime.html')