[데이터분석] 서울시 범죄 현황

·2023년 4월 1일
0
post-thumbnail

🔎 서울시 범죄 현황 분석


1. 강남 3구 범죄 현황 데이터 불러오기

import pandas as pd
import numpy as np

crime_raw_data=pd.read_csv(
    "../data/02. crime_in_Seoul.csv",
    #숫자값들이 콤마(,)를 사용하고 있어서 문자로 인식될 수 있다.
    #천단위 구분이라고 알려주면 콤마를 제거하고 숫자형으로 읽음
    thousands=',',
    encoding='euc-kr'
)
crime_raw_data.head(3)


    구분	죄종	발생검거	건수
0	중부	살인	발생	2.0
1	중부	살인	검거	2.0
2	중부	강도	발생	3.0
crime_raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 65534 entries, 0 to 65533
Data columns (total 4 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   구분      310 non-null    object 
 1   죄종      310 non-null    object 
 2   발생검거    310 non-null    object 
 3   건수      310 non-null    float64
dtypes: float64(1), object(3)
memory usage: 2.0+ MB
  • 특정 컬럼에서 unique 조사
  • nan 값 확인
    non-null count와 RangeIndex: 65534 entries, 0 to 65533 비교 >>> nan값 확인
crime_raw_data['죄종'].unique()
array(['살인', '강도', '강간', '절도', '폭력', nan], dtype=object)
crime_raw_data[crime_raw_data['죄종'].isnull()]
구분죄종발생검거건수
310NaNNaNNaN
311NaNNaNNaN
312NaNNaNNaN
313NaNNaNNaN
314NaNNaNNaN
............
65529NaNNaNNaN
65530NaNNaNNaN
65531NaNNaNNaN
65532NaNNaNNaN
65533NaNNaNNaN

65224 rows × 4 columns

null값 제거

crime_raw_data[crime_raw_data['죄종'].notnull()]
구분죄종발생검거건수
0중부살인발생
1중부살인검거
2중부강도발생
3중부강도검거
4중부강간발생
............
305수서강간검거
306수서절도발생
307수서절도검거
308수서폭력발생
309수서폭력검거

310 rows × 4 columns

crime_raw_data=crime_raw_data[crime_raw_data['죄종'].notnull()]
crime_raw_data

번외

PandasPivot Table

  • index, columns, value, aggfunc
df=pd.read_excel('../data/02. sales-funnel.xlsx')
df.head()
AccountNameRepManagerProductQuantityPriceStatus
714466Trantow-BarrowsCraig BookerDebra HenleyCPU130000presented
714466Trantow-BarrowsCraig BookerDebra HenleySoftware110000presented
714466Trantow-BarrowsCraig BookerDebra HenleyMaintenance25000pending
737550Fritsch, Russel and AndersonCraig BookerDebra HenleyCPU135000declined
146832Kiehn-SpinkaDaniel HiltonDebra HenleyCPU265000won

index 설정

# Name 컬럼을 인덱스로 설정 
pd.pivot_table(df,index='Name')
-AccountPriceQuantity
Name
Barton LLC740150350001.000000
Fritsch, Russel and Anderson737550350001.000000
Herman LLC141962650002.000000
Jerde-Hilpert41229050002.000000
Kassulke, Ondricka and Metz30759970003.000000
Keeling LLC6889811000005.000000
Kiehn-Spinka146832650002.000000
Koepp Ltd729833350002.000000
Kulas Inc218895250001.500000
Purdy-Kunde163416300001.000000
Stokes LLC23934475001.000000
Trantow-Barrows714466150001.333333
# 멀티 인덱스 설정
df.pivot_table(index=['Name','Rep','Manager'])
AccountPriceQuantity
NameRepManager
Barton LLCJohn SmithDebra Henley740150350001.000000
Fritsch, Russel and AndersonCraig BookerDebra Henley737550350001.000000
Herman LLCCedric MossFred Anderson141962650002.000000
Jede-HilpertJohn SmithDebra Henley41229050002.000000
Kassulke, Ondricka and MetzWendy YuleFred Anderson30759970003.000000
Keeling LLCWendy YuleFred Anderson6889811000005.000000
Kiehn-SpinkaDaniel HiltonDebra Henley146832650002.000000
Koepp LtdWendy YuleFred Anderson729833350002.000000
Kulas IncDaniel HiltonDebra Henley218895250001.500000
Purdy-KundeCedric MossFred Anderson163416300001.000000
Stokes LLCCedric MossFred Anderson23934475001.000000
Trantow-BarrowsCraig BookerDebra Henley714466150001.333333

value 설정

df.pivot_table(index=['Manager','Rep'],values='Price')
Price
ManagerRep
Debra HenleyCraig Booker20000.000000
Daniel Hilton38333.333333
John Smith20000.000000
Fred AndersonCedric Moss27500.000000
Wendy Yule44250.000000

# Price 컬럼에 sum 연산 적용
df.pivot_table(index=['Manager','Rep'],values='Price',aggfunc=np.sum)
Price
ManagerRep
Debra HenleyCraig Booker80000
Daniel Hilton115000
John Smith40000
Fred AndersonCedric Moss110000
Wendy Yule177000

columns 설정


df.pivot_table(index=['Manager','Rep'],values='Price', columns='Product',aggfunc=np.sum)
-ProductCPUMaintenanceMonitorSoftware
ManagerRep
Debra HenleyCraig Booker65000.05000.0NaN10000.0
-Daniel Hilton105000.0NaNNaN10000.0
-John Smith35000.05000.0NaNNaN
Fred AndersonCedric Moss95000.05000.0NaN10000.0
-Wendy Yule165000.07000.05000.0NaN
# Nan 값 설정 : fill_value
df.pivot_table(index=['Manager','Rep'],values='Price', columns='Product',aggfunc=np.sum,fill_value=0)

-ProductCPUMaintenanceMonitorSoftware
ManagerRep
Debra HenleyCraig Booker65000.05000.0010000.0
-Daniel Hilton105000.00010000.0
-John Smith35000.05000.000
Fred AndersonCedric Moss95000.05000.0010000.0
-Wendy Yule165000.07000.05000.00

2. 서울시 범죄 현황 데이터 정리

crime_raw_data.head()
-구분죄종발생검거건수
0중부살인발생2.0
1중부살인검거2.0
2중부강도발생3.0
3중부강도검거3.0
4중부강간발생141.0
crime_station=crime_raw_data.pivot_table(index='구분',
                                        columns=['죄종','발생검거'],
                                        aggfunc=[np.sum]).copy()
crime_station.head()
sum
건수
죄종강간강도살인절도폭력
발생검거검거발생검거발생검거발생검거발생검거발생
구분
강남269.0339.026.024.03.03.01129.02438.02096.02336.0
강동152.0160.013.014.05.04.0902.01754.02201.02530.0
강북159.0217.04.05.06.07.0672.01222.02482.02778.0
강서239.0275.010.010.010.09.01070.01952.02768.03204.0
관악264.0322.010.012.07.06.0937.02103.02707.03235.0
crime_station.columns=crime_station.columns.droplevel([0,1]) #다중 컬럼에서 특정 컬럼 제거
crime_station.head()
죄종강간강도살인절도폭력
발생검거검거발생검거발생검거발생검거발생검거발생
구분
강남269.0339.026.024.03.03.01129.02438.02096.02336.0
강동152.0160.013.014.05.04.0902.01754.02201.02530.0
강북159.0217.04.05.06.07.0672.01222.02482.02778.0
강서239.0275.010.010.010.09.01070.01952.02768.03204.0
관악264.0322.010.012.07.06.0937.02103.02707.03235.0
crime_station.index
Index(['강남', '강동', '강북', '강서', '관악', '광진', '구로', '금천', '남대문', '노원', '도봉',
       '동대문', '동작', '마포', '방배', '서대문', '서부', '서초', '성동', '성북', '송파', '수서',
       '양천', '영등포', '용산', '은평', '종로', '종암', '중랑', '중부', '혜화'],
      dtype='object', name='구분')
  • 현재 index는 경찰서 이름으로 되어 있다
  • 경찰서 이름으로 구 이름을 알아내야한다.

3. python 모듈 설치

pip 명령

  • python의 공식 모듈 관리자
  • pip list
  • pip install module_name
  • pip uninstall module_name

conda 명령

  • conda list
  • conda install module_name
  • conda uninstall module_name
  • conda install -c channel_name module_name
    • 지정된 배포 채널에서 모듈 설치
  • Window, mac(intel) 환경에서 가능

4. Google Map API 설치

  • API KEY : google cloud를 통해 획득

window, mac(intel)

  • conda install -c conda-forge googlemaps

mac1(M1)

  • pip install googlemaps
import googlemaps
gmaps_key=
gmaps=googlemaps.Client(key=gmaps_key)
gmaps.geocode('서울영등포경찰서',language='ko')
[{'address_components': [{'long_name': '608',
    'short_name': '608',
    'types': ['premise']},
   {'long_name': '국회대로',
    'short_name': '국회대로',
    'types': ['political', 'sublocality', 'sublocality_level_4']},
   {'long_name': '영등포구',
    'short_name': '영등포구',
    'types': ['political', 'sublocality', 'sublocality_level_1']},
   {'long_name': '서울특별시',
    'short_name': '서울특별시',
    'types': ['administrative_area_level_1', 'political']},
   {'long_name': '대한민국',
    'short_name': 'KR',
    'types': ['country', 'political']},
   {'long_name': '150-043',
    'short_name': '150-043',
    'types': ['postal_code']}],
  'formatted_address': '대한민국 서울특별시 영등포구 국회대로 608',
  'geometry': {'location': {'lat': 37.5260441, 'lng': 126.9008091},
   'location_type': 'ROOFTOP',
   'viewport': {'northeast': {'lat': 37.5273930802915,
     'lng': 126.9021580802915},
    'southwest': {'lat': 37.5246951197085, 'lng': 126.8994601197085}}},
  'partial_match': True,
  'place_id': 'ChIJ1TimJLaffDURptXOs0Tj6sY',
  'plus_code': {'compound_code': 'GWG2+C8 대한민국 서울특별시',
   'global_code': '8Q98GWG2+C8'},
  'types': ['establishment', 'point_of_interest', 'police']}]

Pandas의 반복문 명령 iterrows()

  • pandas 데이터 프레임은 대부분 2차원
    for문을 사용하면, n번째라는 지정을 반복해서 가독률이 떨어짐
  • itterows()옵션을 사용하면 편리하다
    결과값을 인덱스와 내용으로 나누어 받는 것만 주의

5. 구글 맵을 이용한 데이터 정리

tmp=gmaps.geocode('서울영등포경찰서',language='ko')

len(tmp) #데이터는 길이는 1
tmp[0]
{'address_components': [{'long_name': '608',
   'short_name': '608',
   'types': ['premise']},
  {'long_name': '국회대로',
   'short_name': '국회대로',
   'types': ['political', 'sublocality', 'sublocality_level_4']},
  {'long_name': '영등포구',
   'short_name': '영등포구',
   'types': ['political', 'sublocality', 'sublocality_level_1']},
  {'long_name': '서울특별시',
   'short_name': '서울특별시',
   'types': ['administrative_area_level_1', 'political']},
  {'long_name': '대한민국', 'short_name': 'KR', 'types': ['country', 'political']},
  {'long_name': '150-043', 'short_name': '150-043', 'types': ['postal_code']}],
 'formatted_address': '대한민국 서울특별시 영등포구 국회대로 608',
 'geometry': {'location': {'lat': 37.5260441, 'lng': 126.9008091},
  'location_type': 'ROOFTOP',
  'viewport': {'northeast': {'lat': 37.5273930802915,
    'lng': 126.9021580802915},
   'southwest': {'lat': 37.5246951197085, 'lng': 126.8994601197085}}},
 'partial_match': True,
 'place_id': 'ChIJ1TimJLaffDURptXOs0Tj6sY',
 'plus_code': {'compound_code': 'GWG2+C8 대한민국 서울특별시',
  'global_code': '8Q98GWG2+C8'},
 'types': ['establishment', 'point_of_interest', 'police']}

원하는 데이터 가져오기

  • 'geometry': {'location': {'lat': 37.5260441, 'lng': 126.9008091}
  • 'formatted_address': '대한민국 서울특별시 영등포구 국회대로 608'
tmp[0].get('geometry')['location']
{'lat': 37.5260441, 'lng': 126.9008091}
# 경ㄷ, 위도 가져오기 
lat=tmp[0].get('geometry')['location']['lat']
lng=tmp[0].get('geometry')['location']['lng']
tmp[0]['formatted_address'].split()[2]
'영등포구'

구별, lat, lng 컬럼 추가

crime_station['구별']=np.nan
crime_station['lat']=np.nan
crime_station['lng']=np.nan
crime_station.head()
죄종강간강도살인절도폭력구별latlng
발생검거검거발생검거발생검거발생검거발생검거발생
구분
강남269.0339.026.024.03.03.01129.02438.02096.02336.0NaNNaNNaN
강동152.0160.013.014.05.04.0902.01754.02201.02530.0NaNNaNNaN
강북159.0217.04.05.06.07.0672.01222.02482.02778.0NaNNaNNaN
강서239.0275.010.010.010.09.01070.01952.02768.03204.0NaNNaNNaN
관악264.0322.010.012.07.06.0937.02103.02707.03235.0NaNNaNNaN
  • 경찰서 이름에서 소속된 구이름 얻기
  • 구이름과 위도, 경도 정보를 저장할 준비
  • 반복문을 이용해서 위 표의 NaN값을 채워준다
for idx, rows in crime_station.iterrows():
    station_name='서울'+str(idx)+'경찰서'
    tmp=gmaps.geocode(station_name,language='ko')
    lat=tmp[0]['geometry']['location']['lat']
    lng=tmp[0]['geometry']['location']['lng']
    address=tmp[0]['formatted_address'].split()[2]
    crime_station.loc[idx,'구별']=address
    crime_station.loc[idx,'lat']=lat
    crime_station.loc[idx,'lng']=lng
    
 
crime_station.head()
죄종강간강도살인절도폭력구별latlng
발생검거검거발생검거발생검거발생검거발생검거
구분
강남269.0339.026.024.03.03.01129.02438.02096.0
강동152.0160.013.014.05.04.0902.01754.02201.0
강북159.0217.04.05.06.07.0672.01222.02482.0
강서239.0275.010.010.010.09.01070.01952.02768.0
관악264.0322.010.012.07.06.0937.02103.02707.0

컬럼 보기쉽게 정리

# 컴럼명 수정 
tmp=[
    crime_station.columns.get_level_values(0)[n]+crime_station.columns.get_level_values(1)[n]
    for n in range(0,len(crime_station.columns.get_level_values(0)))
]

tmp
['강간검거',
 '강간발생',
 '강도검거',
 '강도발생',
 '살인검거',
 '살인발생',
 '절도검거',
 '절도발생',
 '폭력검거',
 '폭력발생',
 '구별',
 'lat',
 'lng']
crime_station.columns=tmp
crime_station.head()
-강간검거강간발생강도검거강도발생살인검거살인발생절도검거절도발생폭력검거폭력발생구별latlng
구분
강남269.0339.026.024.03.03.01129.02438.02096.02336.0강남구37.509435127.066958
강동152.0160.013.014.05.04.0902.01754.02201.02530.0강동구37.528511127.126822
강북159.0217.04.05.06.07.0672.01222.02482.02778.0강북구37.637197127.027305
강서239.0275.010.010.010.09.01070.01952.02768.03204.0양천구37.539783126.829997
관악264.0322.010.012.07.06.0937.02103.02707.03235.0관악구37.474395126.951349
#데이터 저장
crime_station.to_csv('../data/02_crime_in_Seoul_raw.csv',sep=',',encoding='utf-8')

6. 구별 데이터 정리

crime_anal_station=pd.read_csv('../data/02_crime_in_Seoul_raw.csv',index_col=0,encoding='utf-8') #index_col=0  '구분'을 인덱스로 설정
crime_anal_station.head()
-강간검거강간발생강도검거강도발생살인검거살인발생절도검거절도발생폭력검거폭력발생구별latlng
구분
강남269.0339.026.024.03.03.01129.02438.02096.02336.0강남구37.509435127.066958
강동152.0160.013.014.05.04.0902.01754.02201.02530.0강동구37.528511127.126822
강북159.0217.04.05.06.07.0672.01222.02482.02778.0강북구37.637197127.027305
강서239.0275.010.010.010.09.01070.01952.02768.03204.0양천구37.539783126.829997
관악264.0322.010.012.07.06.0937.02103.02707.03235.0관악구37.474395126.951349
crime_anal_gu=crime_anal_station.pivot_table(index='구별',aggfunc=np.sum)
crime_anal_gu.head()
-latlng강간검거강간발생강도검거강도발생살인검거살인발생절도검거절도발생폭력검거폭력발생
구별
강남구75.002925254.144170413.0516.042.039.05.05.01918.03587.03527.04002.0
강동구37.528511127.126822152.0160.013.014.05.04.0902.01754.02201.02530.0
강북구37.637197127.027305159.0217.04.05.06.07.0672.01222.02482.02778.0
관악구37.474395126.951349264.0322.010.012.07.06.0937.02103.02707.03235.0
광진구37.542823127.083839234.0279.06.011.04.04.01057.02636.02011.02392.0
#검거율 생성
# 하나의 컬럼을 다른 컬럼으로 나누기 

crime_anal_gu['강도검거']/crime_anal_gu['강도발생']
구별
강남구     1.076923
강동구     0.928571
강북구     0.800000
관악구     0.833333
광진구     0.545455
구로구     1.300000
금천구     1.000000
노원구     1.500000
도봉구     1.000000
동대문구    1.200000
동작구     1.000000
마포구     1.750000
서대문구    0.800000
서초구     0.769231
성동구     1.666667
성북구     1.000000
송파구     0.800000
양천구     1.000000
영등포구    0.736842
용산구     1.111111
은평구     0.777778
종로구     0.750000
중구      0.875000
중랑구     1.000000
dtype: float64
target=['강간검거율','강도검거율','살인검거율','절도검거율','폭력검거율']
num=['강간검거','강도검거','살인검거','절도검거','폭력검거']
den=['강간발생','강도발생','살인발생','절도발생','폭력발생']

crime_anal_gu[target]=crime_anal_gu[num].div(crime_anal_gu[den].values)*100
crime_anal_gu.head()
-강간검거강간발생강도검거강도발생살인검거살인발생절도검거절도발생폭력검거폭력발생강간검거율강도검거율살인검거율절도검거율폭력검거율
구별
강남구413.0516.042.039.05.05.01918.03587.03527.04002.080.038760107.692308100.00000053.47086788.130935
강동구152.0160.013.014.05.04.0902.01754.02201.02530.095.00000092.857143125.00000051.42531486.996047
강북구159.0217.04.05.06.07.0672.01222.02482.02778.073.27188980.00000085.71428654.99181789.344852
관악구264.0322.010.012.07.06.0937.02103.02707.03235.081.98757883.333333116.66666744.55539783.678516
광진구234.0279.06.011.04.04.01057.02636.02011.02392.083.87096854.545455100.00000040.09863484.071906
# 검거 컬럼 제거
crime_anal_gu.drop(num,axis=1,inplace=True)
crime_anal_gu.head()
-강간발생강도발생살인발생절도발생폭력발생강간검거율강도검거율살인검거율절도검거율폭력검거율
구별
강남구516.039.05.03587.04002.080.038760107.692308100.00000053.47086788.130935
강동구160.014.04.01754.02530.095.00000092.857143125.00000051.42531486.996047
강북구217.05.07.01222.02778.073.27188980.00000085.71428654.99181789.344852
관악구322.012.06.02103.03235.081.98757883.333333116.66666744.55539783.678516
광진구279.011.04.02636.02392.083.87096854.545455100.00000040.09863484.071906
# 컬럼 이름 변경
crime_anal_gu.rename(columns={'강간발생':'강간',
                              '강도발생':'강도',
                             '살인발생':'살인',
                             '폭력발생':'폭력',
                             '절도발생':'절도'},inplace=True)
crime_anal_gu.head()
-강간강도살인절도폭력강간검거율강도검거율살인검거율절도검거율폭력검거율
구별
강남구516.039.05.03587.04002.080.038760107.692308100.00000053.47086788.130935
강동구160.014.04.01754.02530.095.00000092.857143125.00000051.42531486.996047
강북구217.05.07.01222.02778.073.27188980.00000085.71428654.99181789.344852
관악구322.012.06.02103.03235.081.98757883.333333116.66666744.55539783.678516
광진구279.011.04.02636.02392.083.87096854.545455100.00000040.09863484.071906

7. 범죄 데이터 정렬을 위한 데이터 정리

데이터 정규화

# 정규화 : 최고값 : 1, 최소값 : 0
crime_anal_gu['강도']/crime_anal_gu['강도'].max()
구별
강남구     1.000000
강동구     0.358974
강북구     0.128205
관악구     0.307692
광진구     0.282051
구로구     0.256410
금천구     0.179487
노원구     0.153846
도봉구     0.128205
동대문구    0.256410
동작구     0.179487
마포구     0.102564
서대문구    0.128205
서초구     0.333333
성동구     0.076923
성북구     0.205128
송파구     0.384615
양천구     0.435897
영등포구    0.487179
용산구     0.230769
은평구     0.230769
종로구     0.307692
중구      0.205128
중랑구     0.358974
Name: 강도, dtype: float64
col=['강도','살인','강간','절도','폭력']
crime_anal_norm=crime_anal_gu[col]/crime_anal_gu[col].max()
crime_anal_norm.head()
강도살인강간절도폭력
구별
강남구1.0000000.3571431.0000000.9771180.733773
강동구0.3589740.2857140.3100780.4777990.463880
강북구0.1282050.5000000.4205430.3328790.509351
관악구0.3076920.4285710.6240310.5728680.593143
광진구0.2820510.2857140.5406980.7180600.438577
#검거율 추가
col2=['강간검거율','강도검거율','살인검거율','절도검거율','폭력검거율']
crime_anal_norm[col2]=crime_anal_gu[col2]
crime_anal_norm.head()
-강도살인강간절도폭력강간검거율강도검거율살인검거율절도검거율폭력검거율
구별
강남구1.0000000.3571431.0000000.9771180.73377380.038760100.000000100.00000053.47086788.130935
강동구0.3589740.2857140.3100780.4777990.46388095.00000092.857143100.00000051.42531486.996047
강북구0.1282050.5000000.4205430.3328790.50935173.27188980.00000085.71428654.99181789.344852
관악구0.3076920.4285710.6240310.5728680.59314381.98757883.333333100.00000044.55539783.678516
광진구0.2820510.2857140.5406980.7180600.43857783.87096854.545455100.00000040.09863484.071906
# CCTV 자료에서 인구수와 CCTV 수 추가

result_cctv=pd.read_csv('../data/01_Seoul_CCTV_Data.csv',index_col='자치구', encoding='utf-8')

crime_anal_norm[['인구수','CCTV']]=result_cctv[['인구수','소계']]
crime_anal_norm.head()
-강도살인강간절도폭력강간검거율강도검거율살인검거율절도검거율폭력검거율인구수CCTV
구별
강남구1.0000000.3571431.0000000.9771180.73377380.038760100.000000100.00000053.47086788.1309355349883238
강동구0.3589740.2857140.3100780.4777990.46388095.00000092.857143100.00000051.42531486.9960474644901010
강북구0.1282050.5000000.4205430.3328790.50935173.27188980.00000085.71428654.99181789.344852298622831
관악구0.3076920.4285710.6240310.5728680.59314381.98757883.333333100.00000044.55539783.6785165007502109
광진구0.2820510.2857140.5406980.7180600.43857783.87096854.545455100.00000040.09863484.071906351073878
# 정규화된 범죄발생 건수 전체의 평균을 구해서 범죄컬럼 대표값으로 사용
col=['강도','살인','강간','절도','폭력']
crime_anal_norm['범죄']=np.mean(crime_anal_norm[col],axis=1)
crime_anal_norm.head()

# 정규화된 검거발생 건수 전체의 평균을 구해서 검거컬럼 대표값으로 사용
import numpy as np
col=['강간검거율','강도검거율','살인검거율','절도검거율','폭력검거율']
crime_anal_norm['검거']=np.mean(crime_anal_norm[col],axis=1)

crime_anal_norm.head()
-강도살인강간절도폭력강간검거율강도검거율살인검거율절도검거율폭력검거율인구수CCTV범죄검거
구별
강남구1.0000000.3571431.0000000.9771180.73377380.038760100.000000100.00000053.47086788.13093553498832380.81360784.328112
강동구0.3589740.2857140.3100780.4777990.46388095.00000092.857143100.00000051.42531486.99604746449010100.37928985.255701
강북구0.1282050.5000000.4205430.3328790.50935173.27188980.00000085.71428654.99181789.3448522986228310.37819676.664569
관악구0.3076920.4285710.6240310.5728680.59314381.98757883.333333100.00000044.55539783.67851650075021090.50526178.710965
광진구0.2820510.2857140.5406980.7180600.43857783.87096854.545455100.00000040.09863484.0719063510738780.45302072.517393

Seaborn

예제1 : seaborn 기초

x=np.linspace(0,14,100) #0부터 14까지 100개의 데이터 생성 
y1=np.sin(x)
y2=2*np.sin(x+0.5)
y3=3*np.sin(x+1)
y4=4*np.sin(x+1.5)

plt.figure(figsize=(10,6))
plt.plot(x,y1,x,y2,x,y3,x,y4)
plt.grid()
plt.show()

#sns.set_style
#'white', 'whitegrid', 'dark', 'darkgrid'
sns.set_style('dark')
plt.figure(figsize=(10,6))
plt.plot(x,y1,x,y2,x,y3,x,y4)
plt.show()

#sns.set_style
sns.set_style('whitegrid')
plt.figure(figsize=(10,6))
plt.plot(x,y1

예제2: seaborn tips data

  • boxplot
  • swarmplot
  • lmplot
tips=sns.load_dataset('tips')
tips
-total_billtipsexsmokerdaytimesize
016.991.01FemaleNoSunDinner2
110.341.66MaleNoSunDinner3
221.013.50MaleNoSunDinner3
323.683.31MaleNoSunDinner2
424.593.61FemaleNoSunDinner4
........................
23929.035.92MaleNoSatDinner3
24027.182.00FemaleYesSatDinner2
24122.672.00MaleYesSatDinner2
24217.821.75MaleNoSatDinner2
24318.783.00FemaleNoThurDinner2

244 rows × 7 columns

tips.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 244 entries, 0 to 243
Data columns (total 7 columns):
 #   Column      Non-Null Count  Dtype   
---  ------      --------------  -----   
 0   total_bill  244 non-null    float64 
 1   tip         244 non-null    float64 
 2   sex         244 non-null    category
 3   smoker      244 non-null    category
 4   day         244 non-null    category
 5   time        244 non-null    category
 6   size        244 non-null    int64   
dtypes: category(4), float64(2), int64(1)
memory usage: 7.4 KB
#boxplot
plt.figure(figsize=(8,6))
sns.boxplot(x=tips['total_bill'])
plt.show


#boxplot
plt.figure(figsize=(8,6))
sns.boxplot(x='day',y='total_bill',data=tips)
plt.show()

# boxplot hue, pallete option
plt.figure(figsize=(8,6))
sns.boxplot(x='day',y='total_bill',data=tips,hue='smoker', palette='Set3') # set 1~3 까지 있음 
plt.show()

#swarmplot

plt.figure(figsize=(8,6))
sns.swarmplot(x='day',y='total_bill',data=tips, color="0.5") # color : 0-1 사이 검은색부터 흰색 사이의 값 조정  
plt.show()

### boxplot with swarmplot

plt.figure(figsize=(8,6))
sns.boxplot(x='day',y='total_bill',data=tips)  
sns.swarmplot(x='day',y='total_bill',data=tips, color='0.3')
plt.show()

#lmplot total_bill과 tip사이의 관계 파악 

sns.set_style('darkgrid')
sns.lmplot(x='total_bill',y='tip',data=tips, height=7) 

#hue option

sns.set_style('darkgrid')
sns.lmplot(x='total_bill',y='tip',data=tips,height=7,hue='smoker')

예제3: flights data

  • heatmap
flights=sns.load_dataset('flights')
flights.head()
-yearmonthpassengers
01949Jan112
11949Feb118
21949Mar132
31949Apr129
41949May121
flights.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 144 entries, 0 to 143
Data columns (total 3 columns):
 #   Column      Non-Null Count  Dtype   
---  ------      --------------  -----   
 0   year        144 non-null    int64   
 1   month       144 non-null    category
 2   passengers  144 non-null    int64   
dtypes: category(1), int64(2)
memory usage: 2.9 KB
#pivot
#index,columns,values 

flights=flights.pivot(index='month',columns='year',values='passengers')

flights
year194919501951195219531954195519561957195819591960
month
Jan112115145171196204242284315340360417
Feb118126150180196188233277301318342391
Mar132141178193236235267317356362406419
Apr129135163181235227269313348348396461
May121125172183229234270318355363420472
Jun135149178218243264315374422435472535
Jul148170199230264302364413465491548622
Aug148170199242272293347405467505559606
Sep136158184209237259312355404404463508
Oct119133162191211229274306347359407461
Nov104114146172180203237271305310362390
Dec118140166194201229278306336337405432
# heatmeap

plt.figure(figsize=(10,8))
sns.heatmap(data=flights,annot=True, fmt='d') # annot=True 데이터 값 표시 , fmt = 'd' 정수형 표현
plt.show()

# colormap

plt.figure(figsize=(10,8))
sns.heatmap(data=flights,annot=True, fmt='d', cmap='YlGnBu') 
plt.show()

#### 예제4: iris data
iris=sns.load_dataset('iris')
iris.tail()
-sepal_lengthsepal_widthpetal_lengthpetal_widthspecies
1456.73.05.22.3virginica
1466.32.55.01.9virginica
1476.53.05.22.0virginica
1486.23.45.42.3virginica
1495.93.05.11.8virginica
# paitplot 

sns.set_style('ticks')
sns.pairplot(iris)
plt.show()

#hue option

sns.pairplot(iris,hue='species')
plt.show()

profile
개발하고싶은사람

0개의 댓글