4.29
[주피터 노트북 실행]
1. anaconda 실행
2. conda activate ds_study 입력
3. cd Documents 입력
4. cd ds_study 입력
5. jupyter notebook 입력
[예시 알고 싶을 때]
shift + tap
[Pandas 기초]
[pandas in jupyter notebook]
판다스 열기
import pandas as pd
CCTV_Seoul = pd.read_csv("..\data\01. Seoul_CCTV.csv")
제목설정
앞에 # 넣고 제목 쓴 다음 esc키 누른 후 "m" 누르면 파란색으로 바뀜, 그 이후 shift + enter 누르면 제목 설정 됨
#이 많아질수록 제목의 크기가 작아짐
행 위로 추가
추가할 행 누르고 esc키 누른 후 "a" 누르기
앞에서부터 자료 열기(괄호에 숫자 입력하면 앞에서부터 n번째 자료)
CCTV_Seoul.head()
뒤에서부터 자료 열기(괄호에 숫자 입력하면 뒤에서부터 n번째 자료)
CCTV_Seoul.tail()
이름변경
CCTV_Seoul.rename(columns={CCTV_Seoul.columns[0]: "구별"}
index, column, values: 행(가로), 열(세로), 자료들
CCTV_Seoul.rename(columns={CCTV_Seoul.columns[0]: "구별"}, inplace=True)
<판다스 엑셀 읽기에 관한 설명들>
https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html
[Series]
<날짜 데이터>
dates = pd.date_range("20240101", periods=6)
실행하면 '2024-01-01', ~~ 6일까지 출력 됨
[DataFrame]
가장 많이 사용되는 데이터형
pd.Series()
pd.DataFrame()
- index, value, column
cf. 표준정규분포에서 샘플링한 난수 생성
data = np.random.randn(6,4)
data
데이터 프레임 만들기
df= pd.DataFrame(data, index=dates, columns=["A", "B", "C", "D"])
df
cf. 아예 내가 처음으로 데이터를 만들 때
ex
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
DataFrame 기본정보 확인(각 컬럼 크기, 데이터 형태 확인할 수 있음)
df.info()
DataFrame의 기술통계적 정보 확인
df.describe()
[데이터 정렬]
df.sort_values(by="정렬기준", ascending=True/False)
[특정 컬럼만 읽기]
df["특정 컬럼"] : 특정 컬럼만 읽음
[offset index]
인덱스나 컬럼의 이름으로 slice하는 경우는 끝을 포함!!!
df.loc(:,["A", "B"]]: 모든 행 & A열 & B열 읽음)
[loc]
ex. df.loc[:,["A","B"]] / df.loc["20210102": "20210104", ["A", "B"]]
[iloc]
ex. df.iloc[3] / df.iloc[3,2]
[condition]
ex. df[df["A"] > 0]: 출력하면 0보다 큰 A 값이 있는 행들만 출력 됨
ex1. df[df > 0]: 출력하면 0보다 작은 값들은 NaN으로 출력
ex2. df["E"].isin(["two", "four"]): E열에 "two" 또는 "four" 가 있으면 True, 아니면 False
ex3. df[df["E"].isin(["two", "four"])]: E열에 "two" 또는 "four" 가 들어간 행만 선택 됨
[컬럼 추가]
ex. df["E"] = ["one", "one","two","three","four","seven"]
[isin]
ex. df["E"].isin(["two"]) : 결과는 T/F
[특정 컬럼 제거]
del
del df["특정 컬럼"]: 특정 컬럼 제거됨
drop
df.drop(["특정 컬럼"], axis=1) # axis=0 가로, axis=1 세로
[apply]
ex. df["A"].apply("sum")
df["A"].apply("min"), df["A"].apply("max")
df["A"].apply(np.sum)
[데이터 합치기]
pd.concat()
pd.merge()
pd.join()
[pd.merge()]
두 데이터 프레임에서 컬럼이나 인덱스를 기준으로 잡고 병합하는 방법
기준이 되는 컬럼이나 인덱스를 키값이라고 합니다
기준이 되는 키값은 두 데이터 프레임에 모두 포함되어 있어야 합니다
교집합
pd.merge(left, right, how = "inner", on = "key")
how = "inner" 는 안써도 됨(안쓰면 생략)
한쪽 기준
pd.merge(left, right, how = "left" ,on = "key")
pd.merge(left, right, how = "right", on = "key")
양쪽 합집합
pd.merge(left, right, how="outer", on = "key")
[인덱스 변경]
data_result.set_index("구별", inplace=True)
[상관계수]
data_result.corr()
5.3
[matplotlib 기초]
import matplotlib.pyplot as plt
from matplotlib import rc
rc("font", family="Malgun Gothic")
get_ipython().run_line_magic("matplotlib", "inline")
[matplotlib 그래프 기본 형태]
plt.figure(figsize=(10,6))
plt.plot([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 1, 2, 3, 4, 2, 3, 5, -1, 3])
plt.show()
[예제1. 그래프 기초]
<삼각함수 그리기>
np.arange(a, b, s): a부터 b까지 s의 간격
np.sin(value)
예시
import numpy as np
t = np.arange(0, 12, 0.01)
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) #False면 격자 없음
plt.title("제목")
plt.xlabel("x축 제목")
plt.ylabel("y축 제목")
plt.plot(t, np.sin(t), label="데이터 의미")
plt.plot(t, np.cos(t), label= "데이터 의미")
예시
plt.figure(figsize=(10,6))
plt.plot(t, np.sin(t), label="sin")
plt.plot(t, np.cos(t), label= "cos")
plt.grid(True)
plt.legend(loc="lower left") #범례
plt.title("Example of sinewave")
plt.xlabel("time")
plt.ylabel("Amlitude") #진폭
plt.show()

cf. 함수로 선언
맨위에 def 함수명 쓰고 그래프 선언한거 드래그 후 tap 눌러 들여쓰기 해주기
[예제2. 그래프 커스텀]
예시1. 그래프 1개일 때
t = [0, 1, 2, 3, 4, 5, 6]
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="red",
linestyle="-",
marker="o",
markerfacecolor="blue",
markersize=15,
plt.xlim([-0.5, 6.5])
plt.ylim([0.5, 9.5])
plt.show
drawGraph()

예시2. 그래프 3개일 때
t = np.arange(0,5,0.5)
t
plt.figure(figsize=(10,6))
plt.plot(t, t, "r--")
plt.plot(t, t2, "bs")
plt.plot(t, t3, "g^")
plt.show()

[예제3. scatter plot]
t = np.array(range(0,10))
y = np.array([9,8,7,9,8,3,2,4,3,4])
def drawGraph():
plt.figure(figsize=(20,6))
plt.scatter(t,y)
plt.show()
drawGraph()
colormap = t
def drawGraph():
plt.figure(figsize=(20,6))
plt.scatter(t,y,s=100, c=colormap, marker="<")
plt.colorbar()
plt.show()
drawGraph()
[예제4.pandas에서 plot 그리기]
matplotlib을 가져와서 사용합니다
data_result["인구수"].plot(kind="bar", figsize=(10,10))
구별 기준으로 인구수를 표시
kind="bar"는 바 그래프를 사용한다는 뜻
cf. kind="barh"를 사용하면 가로로 눕혀진 그래프로 바뀜
그래프 그리기 전 기본적으로 설정해줘야 할 것
import matplotlib.pyplot as plt
from matplotlib import rc
rc("font", family = "Malgun Gothic")
get_ipython().run_line_magic("matplotlib", "inline")
예시
import numpy as np
fp1 = np.polyfit(data_result["인구수"], data_result["소계"], 1)
fp1
f1 = np.poly1d(fp1)
f1
인구가 40만인 구에서 서울시의 전체 경향에 맞는 적당한 CCTV 수는?
fx = np.linspace(100000, 700000,100)
- 경향선을 그리기 위한 x 데이터 생성
- np.linspace(a,b,n): a부터 b까지 n개의 등간격 데이터 생성
def drawGraph():
plt.figure(figsize=(14,10))
plt.scatter(data_result["인구수"], data_result["소계"], s=50)
plt.plot(fx, f1(fx), ls="dashed", lw=3, color="g")
plt.xlabel("인구수")
plt.ylabel("CCTV")
plt.grid(True)
plt.show()
drawGraph()




5.4
[pip 명령]
[conda 명령]
: pip를 사용하면 conda 환경에서 dependency 관리가 정확하지 않을 수 있다.
: 아나콘다에서는 가급적 conda 명령으로 모듈 관리하는 것이 좋음!
: 모든 모듈이 conda로 설치되는 것은 아님!
[googleMaps]
import googlemaps
gmaps_key = 'AIzaSyC8pBZnXPfrh4ZxSR_N9M0ajdNLmGUSVQw'
gmaps = googlemaps.Client(key=gmaps_key)
gmaps.geocode("서울영등포경찰서", language="ko")
5.5