Python
서울특별시 구별 CCTV 현황 분석
이부일
2018. 2. 10. 22:14
[출처] 파이썬으로 데이터 주무르기, 민형기 지음, BJPublic, p23 ~ 72
In [70]:
# 패키지 로딩하기
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
%matplotlib inline
In [3]:
# csv 데이터 불러오기
cctv_seoul = pd.read_csv("01. CCTV_in_Seoul.csv", encoding = "UTF-8")
In [5]:
# 데이터의 일부 보기
cctv_seoul.head()
Out[5]:
In [6]:
# 데이터의 변수명 보기
cctv_seoul.columns
Out[6]:
In [7]:
# 첫 번째 변수명 보기
cctv_seoul.columns[0]
Out[7]:
In [10]:
# 변수명 변경하기
cctv_seoul.rename(columns = {cctv_seoul.columns[0] : "구별"}, inplace = True)
cctv_seoul.head()
Out[10]:
In [52]:
# excel 데이터 불러오기
pop_seoul = pd.read_excel("01. population_in_Seoul.xls", encoding="UTF-8")
pop_seoul.head()
Out[52]:
In [53]:
# excel 데이터 불러오기
pop_seoul = pd.read_excel("01. population_in_Seoul.xls",
encoding = "UTF-8",
header = 2,
parse_cols = "B, D, G, J, N")
pop_seoul.head()
Out[53]:
In [54]:
# 변수명 변경하기
pop_seoul.rename(columns = {pop_seoul.columns[0] : "구별",
pop_seoul.columns[1] : "인구수",
pop_seoul.columns[2] : "한국인",
pop_seoul.columns[3] : "외국인",
pop_seoul.columns[4] : "고령자",}, inplace = True)
pop_seoul.head()
Out[54]:
In [16]:
# 행 이름
pop_seoul.index
Out[16]:
In [17]:
# 데이터의 정보
pop_seoul.info()
In [18]:
# 기술통계량 구하기
pop_seoul.describe()
Out[18]:
In [21]:
# 정렬하기 : 내림차순
pop_seoul.sort_values(by = "인구수", ascending = False)
Out[21]:
In [22]:
# 특정 변수만 불러오기
pop_seoul["인구수"]
Out[22]:
In [23]:
# 일부의 행만 불러오기
pop_seoul[0:3]
Out[23]:
In [29]:
# 하나의 열만 추출하기
pop_seoul.loc[: , "구별"]
Out[29]:
In [30]:
# 한 개 이상의 열을 추출하기
pop_seoul.loc[: , ["구별", "인구수"]]
Out[30]:
In [34]:
# 특정한 행과 특정한 열만 추출하기
# 구별 열만 추출하기
pop_seoul.loc[pop_seoul.구별 == "양천구", "인구수"]
Out[34]:
In [35]:
# iloc를 이용한 특정한 행과 열을 추출하기
pop_seoul.iloc[1:3, 2:4]
Out[35]:
In [37]:
# 데이터 복사하기
pop_seoul2 = pop_seoul.copy()
pop_seoul2.head()
Out[37]:
In [42]:
# 구별에 용산구가 있는지를 확인
pop_seoul["구별"].isin(["용산구"])
Out[42]:
In [44]:
# 양적 자료인 열에 대한 누적합 구하기
pop_seoul.iloc[:, 1:4].apply(np.cumsum)
Out[44]:
In [49]:
# 양적 자료인 열에 대한 범위 구하기
pop_seoul.iloc[:, 1:4].apply(lambda x: x.max() - x.min())
Out[49]:
In [55]:
# 첫 행 제거하기
pop_seoul.drop([0], inplace = True)
pop_seoul.head()
Out[55]:
In [56]:
# 구별 목록 보기
pop_seoul["구별"].unique()
Out[56]:
In [57]:
# NAN 추출하기
pop_seoul[pop_seoul["구별"].isnull()]
Out[57]:
In [58]:
# 구별에 NAN을 포함하는 행 삭제하기
pop_seoul.drop([26], inplace = True)
pop_seoul.head()
In [60]:
# 새로운 변수 만들기
pop_seoul["외국인비율"] = (pop_seoul["외국인"] / pop_seoul["인구수"])*100
pop_seoul["고령자비율"] = (pop_seoul["고령자"] / pop_seoul["인구수"])*100
pop_seoul.head()
Out[60]:
In [61]:
# 인구수를 기준으로 내림차순으로 정렬하기
pop_seoul.sort_values(by = "인구수", ascending = False)
pop_seoul.head()
Out[61]:
In [62]:
# CCTV와 인구 데이터 합치기
seoul = pd.merge(cctv_seoul, pop_seoul, on = "구별")
seoul.head()
Out[62]:
In [65]:
# 특정한 열 삭제하기
del seoul["2013년도 이전"]
del seoul["2014년"]
del seoul["2015년"]
del seoul["2016년"]
seoul.head()
Out[65]:
In [66]:
# 기준 세팅하기
seoul.set_index("구별", inplace = True)
seoul.head()
Out[66]:
In [67]:
# 상관계수 구하기
np.corrcoef(seoul["고령자비율"], seoul["소계"])
Out[67]:
In [68]:
# 상관계수 구하기
np.corrcoef(seoul["외국인비율"], seoul["소계"])
Out[68]:
In [69]:
# 상관계수 구하기
np.corrcoef(seoul["인구수"], seoul["소계"])
Out[69]:
In [84]:
# 가로막대 그래프
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
seoul["소계"].plot(kind = "barh", grid = True, figsize = (10, 10))
plt.show()
In [85]:
# 가로막대 그래프
seoul["소계"].sort_values().plot(kind = "barh", grid = True, figsize = (10, 10))
plt.show()
In [86]:
seoul["CCTV비율"] = (seoul["소계"] / seoul["인구수"])*100
seoul["CCTV비율"].sort_values().plot(kind = "barh", grid = True, figsize = (10, 10))
plt.show()
In [90]:
# 산점도 작성하기
plt.figure(figsize = (10, 10))
plt.scatter(seoul["인구수"], seoul["소계"], s = 50)
plt.xlabel("인구수")
plt.ylabel("CCTV")
plt.grid()
plt.show()
In [92]:
fp1 = np.polyfit(seoul["인구수"], seoul["소계"], 1)
f1 = np.poly1d(fp1)
fx = np.linspace(100000, 700000, 100)
In [93]:
plt.figure(figsize = (10, 10))
plt.scatter(seoul["인구수"], seoul["소계"], s = 50)
plt.plot(fx, f1(fx), ls = "dashed", lw = 3, color = "g")
plt.xlabel("인구수")
plt.ylabel("CCTV")
plt.grid()
plt.show()
In [94]:
fp1 = np.polyfit(seoul["인구수"], seoul["소계"], 1)
f1 = np.poly1d(fp1)
fx = np.linspace(100000, 700000, 100)
seoul["오차"] = np.abs(seoul["소계"] - f1(seoul["인구수"]))
seoul_sort = seoul.sort_values(by = "오차", ascending = False)
seoul_sort.head()
Out[94]:
In [95]:
plt.figure(figsize = (10, 10))
plt.scatter(seoul["인구수"], seoul["소계"], c = seoul["오차"], s = 50)
plt.plot(fx, f1(fx), ls = "dashed", lw = 3, color = "g")
for n in range(10):
plt.text(seoul_sort["인구수"][n]*1.02, seoul_sort["소계"][n]*0.98, seoul_sort.index[n], fontsize = 15)
plt.xlabel("인구수")
plt.ylabel("CCTV")
plt.colorbar()
plt.grid()
plt.show()