
--> 데이터 분석가의 역할과 기술:
프로그래밍 기술, 도메인 지식, 수학 및 통계 지식을 모두 필요로 함. 다양한 기술들이 조화를 이루어야 효과적인 데이터 분석이 가능!
데이터 분석 도구:
파이썬과 R이 대표적인 데이터 분석 언어
파이썬 : 비즈니스 문제를 해결하는 경우, CSV 파일을 읽어와 Pandas 라이브러리를 활용해 데이터를 분석
🔹HTML에서 데이터 추출 예제🔹
1. yes24의 상세 페이지에서 쪽수 정보를 포함한 태그를 찾아서 데이터 추출
2. 추출한 데이터를 파이썬 문자열 메소드를 사용하여 가공
❗데이터 정제의 중요성
drop : 특정 열 삭제
dropna : 'NaN' 값을 포함한 열 삭제
drop : 특정 행 삭제
groupby : 특정 열을 기준으로 데이터를 그룹화하고, 그룹별로 합계를 구하는 등의 작업 수행 가능
sum : 그룹화된 데이터의 합계를 계산
데이터가 비어있거나 잘못된 값이 있을 수 있음
예제
. ^ $ * + ? { } [ ] \ | ( )
1) [ ] : 대괄호 안에 포함된 문자들 중 하나와 매치를 뜻함
[abc] : abc 중 하나와 매치
'a' : a와 매치
'boy' : b와 매치
'edf' : 어느 문자와도 매치되지 않음
[a-c] : [abc]와 같음 --> -를 사용하면 두 문자 사이의 범위를 의미
[0-3] : [0123]과 같음
[a-zA-Z] : 알파벳 모두
[0-9] : 숫자
^ : 반대를 의미
[^0-9] : 숫자가 아닌 문자만 매치
3) + : 앞의 문자를 0번 이상 반복하는 것
3) + : 앞의 문자를 0번 이상 반복하는 것
3) ? : 앞의 문자를 0번 or 1번 반복하는 것
3) . : 1글자(문자)가 있다는 것
3) {3,5} : 3이상 5이하 반복하는 것
자주 사용하는 문자 클래스
그래프는 데이터를 한눈에 보기 쉽게 만들고, 시각적으로 이해하기 쉽도록 도와줌
import matplotlib.pyplot as plt
plt.scatter(x, y)
plt.scatter(x, y, alpha=0.1)
plt.show()
plt.hist(data, bins=5)
plt.show()
#numpy의 histogram 함수를 사용하여 정확한 구간 값을 얻을 수 있음
import numpy as np
hist, bin_edges = np.histogram(data, bins=5)
data = np.random.randn(1000)
plt.hist(data, bins=30)
plt.show()
plt.boxplot(data)
plt.yscale('log') #y축 로그 스케일로 변경
plt.show()
Matplotlib에서 그래프를 그리기 위해서는 먼저 Figure 객체를 생성해야 함. Figure 객체는 그래프의 전체적인 틀을 담당!
import matplotlib.pyplot as plt
fig = plt.figure()
# 1행 2열 중 첫 번째 서브플롯
ax1 = fig.add_subplot(1, 2, 1)
# 1행 2열 중 두 번째 서브플롯
ax2 = fig.add_subplot(1, 2, 2)
# 2행 1열의 서브플롯
fig, axs = plt.subplots(2, 1)
ax1.plot(x, y)
ax2.scatter(x, y)
fig = plt.figure(figsize=(10, 6))
fig = plt.figure(dpi=144
import matplotlib.pyplot as plt
import matplotlib as mpl
# 그래프의 기본 크기 변경
mpl.rcParams['figure.figsize'] = (10, 6)
# 선의 기본 너비 변경
mpl.rcParams['lines.linewidth'] = 2
# 제목의 기본 크기 변경
mpl.rcParams['axes.titlesize'] = 'large'
#x/y축 틱 라벨 글꼴 크기 변경
mpl.rcParams['x/ytick.labelsize'] = 'small'
# 변경된 설정을 적용한 그래프 그리기
plt.plot([1, 2, 3], [4, 5, 6])
plt.title('Example Plot')
plt.show()
예제
fig, axs = plt.subplots(2, 1, figsize=(8, 10))
axs[0].scatter(x, y, alpha=0.5)
axs[0].set_title('Scatter Plot')
axs[1].hist(data, bins=30, alpha=0.75)
axs[1].set_title('Histogram')
plt.show()
import matplotlib.pyplot as plt
# 예시 데이터
count_by_year = {2000: 120, 2001: 150, 2002: 170, 2003: 180, 2004: 190}
plt.plot(list(count_by_year.keys()), list(count_by_year.values()))
#선 스타일 바꾸기
plt.plot(list(count_by_year.keys()), list(count_by_year.values()), marker='o', linestyle='--', color='r')
plt.xlabel('Year')
plt.ylabel('Count')
plt.title('Books Borrowed by Year')
plt.show()
#그래프에 텍스트 추가하기
plt.plot(list(count_by_year.keys()), list(count_by_year.values()), marker='o', linestyle='--', color='r')
plt.xlabel('Year')
plt.ylabel('Count')
plt.title('Books Borrowed by Year')
for idx, val in count_by_year.items():
plt.annotate(f'{val}', xy=(idx, val), xytext=(5, 5), textcoords='offset points')
plt.show()
# 예시 데이터
count_by_subject = {'Math': 120, 'Science': 150, 'English': 170}
plt.bar(list(count_by_subject.keys()), list(count_by_subject.values()))
plt.xlabel('Subject')
plt.ylabel('Count')
plt.title('Books Borrowed by Subject')
plt.show()
#막대에 값 표시 : annotate() 함수 사용
bars = plt.bar(list(count_by_subject.keys()), list(count_by_subject.values()))
plt.xlabel('Subject')
plt.ylabel('Count')
plt.title('Books Borrowed by Subject')
for bar in bars:
yval = bar.get_height()
plt.annotate(f'{yval}', xy=(bar.get_x() + bar.get_width() / 2, yval), xytext=(0, 3), textcoords='offset points', ha='center', va='bottom')
plt.show()
세로 막대 그래프 그리기
bars = plt.barh(list(count_by_subject.keys()), list(count_by_subject.values()))
plt.ylabel('Subject')
plt.xlabel('Count')
plt.title('Books Borrowed by Subject')
for bar in bars:
xval = bar.get_width()
plt.annotate(f'{xval}', xy=(xval, bar.get_y() + bar.get_height() / 2), xytext=(5, 0), textcoords='offset points', ha='left', va='center')
plt.show()
fig, ax = plt.subplots()
ax.plot([1, 4, 9, 16])
ax.set_title('Simple Line Graph')
plt.show()
fig, ax = plt.subplots(figsize=(10, 6))
ax.scatter(x=publish_years, y=publishers)
ax.set_title('출판사별 발행년도 도서')
ax.set_xlabel('발행년도')
ax.set_ylabel('출판사')
plt.show()
fig, ax = plt.subplots(figsize=(10, 6))
sizes = [loan * 10 for loan in loan_counts] # 대출 건수에 따라 크기 조정
ax.scatter(x=publish_years, y=publishers, s=sizes)
ax.set_title('출판사별 발행년도 도서')
ax.set_xlabel('발행년도')
ax.set_ylabel('출판사')
plt.show()
fig, ax = plt.subplots(figsize=(10, 6))
ax.scatter(x=publish_years, y=publishers, s=sizes, edgecolors='k', alpha=0.3, linewidths=0.5, c=loan_counts, cmap='viridis')
ax.set_title('출판사별 발행년도 도서')
ax.set_xlabel('발행년도')
ax.set_ylabel('출판사')
plt.colorbar(ax.scatter(x=publish_years, y=publishers, s=sizes, c=loan_counts, cmap='viridis'), ax=ax, label='대출 건수')
plt.show()
fig, ax = plt.subplots(figsize=(10, 6))
sc = ax.scatter(x=publish_years, y=publishers, s=sizes, c=loan_counts, cmap='jet')
ax.set_title('출판사별 발행년도 도서')
ax.set_xlabel('발행년도')
ax.set_ylabel('출판사')
plt.colorbar(sc, ax=ax, label='대출 건수')
plt.show()
from scipy.stats import ttest_ind
# 두 그룹의 데이터
data1 = [20, 21, 19, 22, 20, 23, 21]
data2 = [30, 31, 29, 32, 30, 33, 31]
# t-검정 수행
t_stat, p_value = ttest_ind(data1, data2)
print('t-statistic:', t_stat)
print('p-value:', p_value)
예) 95% 신뢰구간은 표본 평균을 중심으로 1.96 표준편차 내에 모집단의 평균이 포함될 확률이 95%임을 의미
from scipy.stats import permutation_test
# 두 그룹의 데이터
data1 = [20, 21, 19, 22, 20, 23, 21]
data2 = [30, 31, 29, 32, 30, 33, 31]
# 순열 검정 수행
result = permutation_test((data1, data2), statistic=lambda x, y: np.mean(x) - np.mean(y),
permutation_type='independent', alternative='two-sided')
print('p-value:', result.pvalue)
머신러닝은 인공지능의 한 분야로, 컴퓨터를 사용해 데이터를 통해 패턴과 규칙을 학습하는 방법이다. 머신러닝에는 크게 지도학습과 비지도학습이 있다.
지도학습: 정답을 알고 있는 데이터를 사용하여 모델을 훈련시키는 방법
비지도학습: 정답이 없는 데이터를 사용하여 모델을 훈련시키는 방법으로, 데이터의 특성을 분석하거나 군집화하는 데 주로 사용
from sklearn.linear_model import LinearRegression
# 데이터 준비
X = [[1], [2], [3], [4], [5]]
y = [2, 3, 5, 7, 11]
# 모델 훈련
model = LinearRegression()
model.fit(X, y)
# 예측
predictions = model.predict([[6], [7]])
print(predictions)
from sklearn.linear_model import LogisticRegression
# 데이터 준비
X = [[1], [2], [3], [4], [5]]
y = [0, 0, 1, 1, 1]
# 모델 훈련
model = LogisticRegression()
model.fit(X, y)
# 예측
predictions = model.predict([[1.5], [3.5]])
print(predictions)
from sklearn.metrics import accuracy_score, r2_score
# 회귀 모델 평가
r2 = r2_score(y_true, y_pred)
print(f'R² score: {r2}')
# 분류 모델 평가
accuracy = accuracy_score(y_true, y_pred)
print(f'Accuracy: {accuracy}')