- 참고자료 : Numpy 기초 함수 끝장내기 | 파이썬 프로그래밍
- Numerical Python의 줄임말
- 파이썬 패키지 중 하나
- 데이터 구조 외에도 수치 계산을 위해 효율적으로 구현된 기능을 제공
- 데이터 분석에 있어 판다스와 함께 자주 사용되는 패키지
import numpy as np
np.zeors(2)
np.ones(2)
np.arange(4)
# 출력코드
# array([0., 0.])
# array([1., 1.])
# array([0, 1, 2, 3])
# 지난 수업 (서울 CCTV 자료) 이어서
import numpy as np
fp1=np.polyfit(dataResult["인구수"],dataResult["소계"],1)
f1=np.poly1d(fp1) # 경향(trend)
fx= np.linspace(100000,700000,100) #10만~70만 범위에서 100개
# fpl 결과값 : array([1.11155868e-03, 1.06515745e+03])
# f1 결과값 : poly1d([1.11155868e-03, 1.06515745e+03])
# f1(400000) 결과값 (40만 인구에서 서울시 경향에 맞는 CCTV 수는?) : 1509.7809252413335
def drawGraph():
plt.figure(figsize=(14,10))
plt.scatter(dataResult["인구수"],dataResult["소계"], s=50)
plt.plot(fx, f1(fx), ls="dashed", lw=3, color="green") #이 부분의 경향 line
plt.xlabel("인구수")
plt.ylabel("CCTV")
plt.grid(True)
plt.show()
drawGraph()
오차 구하기
dataResult["오차"]=dataResult["소계"]-f1(dataResult["인구수"])
df_sort_f=dataResult.sort_values(by="오차", ascending=False) # 내림차순
df_sort_t=dataResult.sort_values(by="오차", ascending=True) # 오름차순
df_sort_t.head(3)
오차 구별하기
from matplotlib.colors import ListedColormap
#colormap을 사용자가 컬러 지정하기
colorStep = ["#e74c3c","#2ecc71","#95a5a6","#2ecc71","#3498db",""#3498db"]
myCmap=ListedColormap(colorStep)
그래프 코드 입력하기
def drawGraph():
plt.figure(figsize=(14,10))
plt.scatter(dataResult["인구수"],dataResult["소계"], s=50, c=dataResult["오차"], cmap=myCmap)
plt.plot(fx, f1(fx), ls="dashed", lw=3, color="green") #이 부분의 경향 line
#상위, 하위 5개만 도트에 인덱스 명 붙히기
for n in range(5):
#상위 5개
plt.text(df_sort_f["인구수"][n]* 1, #x좌표
df_sort_f["소계"][n]* 1, #y좌표
df_sort_f.index[n])
#하위 5개
plt.text(df_sort_t["인구수"][n]* 1, #x좌표
df_sort_t["소계"][n]* 1, #y좌표
df_sort_t.index[n])
plt.xlabel("인구수")
plt.ylabel("CCTV")
plt.colorbar()
plt.grid(True)
plt.show()
drawGraph()