
【서울시 CCTV 현황 데이터 분석】에 사용된 라이브러리
import pandas as pd
import numpy as np
pd.Series([1, 2, 3, 4])
# 실행결과
# 0 1
# 1 2
# 2 3
# 3 4
# dtype: int64
pd.Series([1, 2, 3, 4], dtype=np.float64)
# 실행결과
# 0 1.0
# 1 2.0
# 2 3.0
# 3 4.0
# dtype: float64
pd.Series([1, 2, 3, "5"])
# 실행결과
# 0 1
# 1 2
# 2 3
# 3 5
# dtype: object
👆 전체를 문자열 데이터로 인식한다.
즉, Series는 한 가지 데이터 타입만 가질 수 있다.
Pandas에서 가장 많이 사용되는 데이터형은 DataFrame이다.
pandas DataFrame 구조 : index, columns, values
import pandas as pd
import numpy as np
dates = pd.date_range("20230101", periods=6)
data = np.random.randn(6, 4) # 표준정규분포에서 샘플링한 난수 생성
df = pd.DataFrame(data, index=dates, columns=["A", "B", "C", "D"])

- Pandas DataFrame 객체의 메서드 : df.head(), df.tail(), df.info(), df.describe()...
- Pandas DataFrame 객체의 속성(변수) : df.index, df.columns, df.values, ...
info() : DataFrame의 개요(기본 정보)를 확인하는 메서드
describe() : DataFrame의 통계적 개요(기본 정보)를 확인하는 메서드
ascending=False이면 내림차순 정렬이다. df.sort_values(by='__column', ascending=True, inplace=True)
df[df['A'] > 0]
df[df > 0]

df['E'] = ['one', 'one', 'two', 'three', 'four', 'seven']
//-> 'E'컬럼을 만들고 리스트의 값들로 채운다.
del df['E']
df.drop(['D'], axis=1) //-> axis=1 세로(column)
df.drop(['20230104'], inplace=True)
left = pd.DataFrame({
"key": ['K0', 'K4', 'K2', 'K3'],
"A": ['A0', 'A1', 'A2', 'A3'],
"B": ['B0', 'B1', 'B2', 'B3']
})
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'}
])
pd.merge(left, right, on="key") //-> "key" 컬럼을 기준으로 병합
pd.merge(left, right, how='inner', on="key") //-> 두 데이터 교집합
pd.merge(left, right, how='outer', on="key") //-> left와 right의 모든 "key"값을 살려 병합
pd.merge(left, right, how='left', on="key") //-> left의 "key"를 기준으로 right 병합
pd.merge(left, right, how='right', on="key") //-> right의 "key"를 기준으로 left 병합

파이썬의 대표 시각화 도구이다.
pyplot은 MATLAB의 시각화 기능들을 담아놓은 것이다.
공식문서를 참고한다.
jupyter notebook 내에서 matplotlib의 결과(그래프)가 output session에 바로 나타나도록 해주는 옵션을 사용한다.
import matplotlib.pyplot as plt
from matplotlib import rc
//# 마이너스 부호 때문에 한글이 깨질 수가 있어 주는 설정
plt.rcParams["axes.unicode_minus"] = False
rc("font", family="Malgun Gothic")
get_ipython().run_line_magic("matplotlib", "inline")
import numpy as np
t = np.arange(0, 12, 0.01) # 0부터 12까지 0.01 간격으로 1200개의 값
y = np.sin(t)
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(loc=1) # plot 라벨의 범례
plt.grid(True)
plt.title("Example of sine and cosine wave")
plt.xlabel("time")
plt.ylabel("Amplitude")
plt.show()
drawGraph()

t = list(range(0, 7)) # t = [0, 1, 2, 3, 4, 5, 6]
y = [1, 4, 5, 8, 9, 5, 3]
def drawGraph():
plt.figure(figsize=(7, 4))
plt.plot(
t,
y,
color="red",
linestyle="--", # "dashed"
marker="o",
markerfacecolor="blue",
markersize=7,
)
# 축의 범위를 지정 (limit값)
plt.xlim([-0.5, 6.5])
plt.ylim([0.5, 9.5])
plt.show()
drawGraph()

t = np.array(range(0, 10))
y = np.array([9, 8, 7, 9, 8, 3, 2, 4, 3, 4])
colormap = t
def drawGraph():
plt.figure(figsize=(10, 6))
plt.scatter(t, y, s=150, marker='<', c=colormap)
plt.colorbar()
drawGraph()
