log.Sehee
[데이터 취업 스쿨 스터디 노트] Pandas Merge / matplotlib 기초 / 데이터 시각화 / 서울시 CCTV 현황 데이터 분석 3 - 4 본문
Zerobase DS School
[데이터 취업 스쿨 스터디 노트] Pandas Merge / matplotlib 기초 / 데이터 시각화 / 서울시 CCTV 현황 데이터 분석 3 - 4
Sehe_e 2024. 7. 30. 21:22CCTV 데이터 훑어보기
# 데이터 조회
CCTV_Seoul.sort_values(by='소계', ascending=False).head(5)
# 기존 컬럼이 없으면 추가, 있으면 수정
CCTV_Seoul['최근증가율'] = (
(CCTV_Seoul['2016년'] + CCTV_Seoul['2015년'] + CCTV_Seoul['2014년']) / CCTV_Seoul['2013년도 이전'] * 100
)
CCTV_Seoul.sort_values(by='최근증가율', ascending=False).head()
인구현황 데이터 훑어보기
pop_Seoul.drop([0], axis=0, inplace=True)
pop_Seoul.head()
# 구별 column의 집합 및 개수 출력
pop_Seoul['구별'].unique(), len(pop_Seoul['구별'].unique())
# 외국인 비율, 고령자 비율
pop_Seoul['외국인비율'] = pop_Seoul['외국인'] / pop_Seoul['인구수'] * 100
pop_Seoul['고령자비율'] = pop_Seoul['고령자'] / pop_Seoul['인구수'] * 100
pop_Seoul.head()
Pandas 데이터 합치기
# 딕셔너리 안의 리스트 형태
left = pd.DataFrame({
'Key': ['K0', 'K4', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']
})
left
right = pd.DataFrame([
{'Key':'K0', 'C':'C0', 'D': 'D0'},
{'Key':'K1', 'C':'C1', 'D': 'D1'},
{'Key':'K2', 'C':'C2', 'D': 'D2'},
{'Key':'K3', 'C':'C3', 'D': 'D3'}
])
right
pd.merge() : 두 데이터 프레임에서 컬럼이나 인덱스 기준으로 병합하는 방법.
기준이 되는 컬럼이나 인덱스를 키값이라고 한다. 기준 키값은 두 데이터 프레임에 모두 포함되어 있어야 한다.
# on = merge 기준 키값 / SQL의 Inner join
pd.merge(left, right, on='Key')
# how = merge 기준 테이블 / SQL의 Left Outer Join & Right Outer Join
pd.merge(left, right, how='left', on='Key')
CCTV 현황 테이블과 인구현황 테이블 병합
테이블 column 확인하기
CCTV_Seoul.head(1)
pop_Seoul.head(1)
구별 column 기준으로 병합
data_result = pd.merge(CCTV_Seoul, pop_Seoul, on='구별')
data_result.head()
필요없는 column 삭제
# del
del data_result['2013년도 이전']
# drop
data_result.drop(['2014년', '2015년', '2016년'], axis=1, inplace=True)
data_result.head()
set_index() : 선택한 컬럼을 데이터 프레임의 인덱스로 변경
data_result.set_index('구별', inplace=True)
data_result.head()
corr() : correlation, 상관계수가 0.2 이상인 데이터를 비교
# 각 컬럼의 상관계수 연산, 연산을 할 수 있는 int & float 타입만 연산 가능, 오브젝트 타입은 NaN으로 출력
data_result.corr()
cctv 비율 column 생성
data_result['CCTV비율'] = data_result['소계'] / data_result['인구수']
data_result['CCTV비율'] = data_result['CCTV비율'] * 100
cctv 비율 많은 순서대로 조회
data_result.sort_values(by='CCTV비율', ascending=False).head()
maplotlib 기초
: python의 대표 시각화 도구. plt로 네이밍하여 사용한다.
pyplot : MATLAB에서 사용하는 시각화 기능을 모아놓음
%matplotlib line : 코드 작성 후 그래프를 시각적으로 나타내기 위한 코드
# 초기 설정
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font', family='Arial Unicode MS') # matplotlib 한글 설정
# %matplotlib inline
get_ipython().run_line_magic('matplotlib', 'inline')
기본 형태
# plt.figure(figsize = (가로, 세로)) / 데이터를 그리기 위한 바탕의 크기 설정.
plt.figure(figsize=(10, 6))
# plt.plot(가로 데이터, 세로 데이터)
plt.plot([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 1, 2, 3, 4, 2, 3, 5, -1, 3])
# 저장 후 조회
plt.show()
삼각함수 그리기
import numpy as np
# np.arange(start, end, step) / start부터 end까지 step의 간격으로 값을 생성하는 시간 배열을 만든다.
t = np.arange(0, 12, 0.01)
# np.sin(value) / value에 sin 함수 적용. 그래프로 시각화했을 때 파장 형태의 사인파를 그린다.
y = np.sin(t)
plt.figure(figsize=(10, 6))
plt.plot(t, np.sin(t))
plt.plot(t, np.cos(t))
plt.show()
격자무늬 추가
plt.grid(True)
그래프 제목 추가
plt.title(그래프 제목)
x축, y축 이름 추가
plt.xlabel(x축 이름)
plt.ylabel(y축 이름)
주황색, 파란색 선 데이터 의미 구분
# 1
plt.plot(가로데이터, 세로데이터)
plt.legend(labels = 데이터 추가순 이름)
# 2
plt.plot(가로데이터, 세로데이터, label=데이터 이름)
plt.legend()
# label 이름 표시 위치 변경
plt.legend(loc=위치 or 위치코드)
# ================== =============
# Location String Location Code
# ================== =============
# 'best' (Axes only) 0
# 'upper right' 1
# 'upper left' 2
# 'lower left' 3
# 'lower right' 4
# 'right' 5
# 'center left' 6
# 'center right' 7
# 'lower center' 8
# 'upper center' 9
# 'center' 10
# ================== =============
기본적으로 컴퓨터가 인식했을 때 빈 공간에 label 생성
그래프 생성 코드 함수화(코드 가독성 증가, 유지보수 용이)
def drawGraph():
plt.figure(figsize=(10, 6))
plt.plot(t, np.sin(t), label='sin')
plt.plot(t, np.cos(t), label='cos')
plt.legend()
plt.grid(True)
plt.title('Example of sinewave')
plt.xlabel('time')
plt.ylabel('Amplitude')
plt.show()
drawGraph()
그래프 커스텀
t = np.arange(0, 5, 0.5)
plt.figure(figsize=(10, 6))
# r, b, g 색 설정 / -, --, s, ^, > 표시 아이콘/선 등 설정
plt.plot(t, t, 'r--') # red 점선
plt.plot(t, t**2, 'bs') # blue square
plt.plot(t, t**3, 'g^') # green 삼각형
plt.show()
t = list(range(0, 7))
y = [1, 4, 5, 8, 9, 5, 3]
def drawGraph():
plt.figure(figsize=[10, 6])
plt.plot(
t,
y,
color = 'green', # 데이터 표시 색
linestyle = 'dashed', # 표시 선 종류
marker = 'o', # 데이터 포인트 모양
markerfacecolor = 'blue', # 포인트 색
markersize = 10 # 포인트 크기
)
# 그래프의 전체적인 레이아웃 및 크기 조정
plt.xlim([-0.5, 6.5]) # x축의 최솟값, 최대값 설정
plt.ylim([0.5, 9.5]) # y축의 최솟값, 최대값 설정
plt.show()
drawGraph()
scatter plot
t = np.array(range(0, 10))
y = np.array([9, 8, 7, 9, 8, 3, 2, 4, 3, 4])
plt.figure(figsize=[10, 6])
plt.scatter(t, y) # scatter는 산점도 형태의 그래프를 그릴 수 있음
plt.show()
colormap = t
def drawGraph():
plt.figure(figsize=(20, 6))
# s = marker size, c = value값에 따라 marker색 지정, cmap = 색상 배열
plt.scatter(t, y, s=50, c=colormap, cmap='magma', marker='>')
# colorbar 표시
plt.colorbar()
plt.show()
drawGraph()
Pandas에서 plot 그리기
data_result.head()
# kind = 그래프 유형 / bar : 세로 막대그래프, barh : 가로 막대그래프
data_result['인구수'].plot(kind='bar', figsize=(10, 10))
소계 컬럼 시각화
def drawGraph():
data_result['소계'].sort_values().plot(
kind='barh', grid=True, figsize=(10, 10), title='가장 CCTV가 많은 구'
);
drawGraph()
내일의 학습 목표
서울시 범죄 현황 1 - 2
Comments