통계 요약 에이전트
에이전트가 생성한 보고서에서 분포 분석, 상관관계, 이상치 탐지를 수행합니다.
통계 요약 에이전트은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
통계 요약이 중요한 이유
원시 데이터는 그 자체로는 유용하지 않은 경우가 많습니다. 데이터 분석 에이전트가 통계 요약을 자동으로 계산하고 숫자를 알기 쉬운 언어의 통찰로 변환할 수 있을 때 진정한 가치를 발휘합니다.
이 수업에서는 핵심 통계 작업인 기술 통계, 상관관계, 이상치 탐지, 분포 식별, 자동 통찰 생성을 다룹니다.
df.describe(): 시작점
df.describe()는 한 번의 호출로 모든 수치 열의 개수, 평균, 표준편차, 최솟값, 사분위수, 최댓값을 계산합니다. 모든 탐색적 데이터 분석에서 일반적으로 가장 먼저 수행하는 단계입니다.
import pandas as pd
df = pd.read_csv('sales_data.csv')
# Basic numeric summary
print(df.describe())
# Also describe categorical columns
print(df.describe(include='object'))
# Custom percentiles
print(df.describe(percentiles=[0.05, 0.25, 0.5, 0.75, 0.95]))
# Convert to clean dict for agent use
def get_numeric_summary(df):
desc = df.describe().round(2)
return {
col: desc[col].to_dict()
for col in desc.columns
}상관관계 행렬
상관관계 행렬은 모든 수치 열 사이의 쌍별 선형 관계를 보여 줍니다. 값의 범위는 -1(강한 음의 상관관계)부터 +1(강한 양의 상관관계)까지입니다. 0에 가까운 값은 선형 관계가 없음을 나타냅니다.
import pandas as pd
import numpy as np
def compute_correlation_matrix(df):
numeric = df.select_dtypes(include='number')
corr = numeric.corr().round(3)
return corr.to_dict()
def find_strong_correlations(df, threshold=0.7):
numeric = df.select_dtypes(include='number')
corr = numeric.corr()
strong = []
cols = corr.columns
for i in range(len(cols)):
for j in range(i + 1, len(cols)): # upper triangle only
val = corr.iloc[i, j]
if abs(val) >= threshold:
strong.append({
'col_a': cols[i],
'col_b': cols[j],
'correlation': round(val, 3),
'direction': 'positive' if val > 0 else 'negative'
})
return sorted(strong, key=lambda x: abs(x['correlation']), reverse=True)이상치 탐지: IQR 방법
사분위 범위(IQR) 방법은 Q3보다 IQR의 1.5배를 초과하여 크거나 Q1보다 작은 값을 이상치로 식별합니다. 이 방법은 극단값에 강건합니다. 이상치가 데이터에 포함되어 있어도 잘 작동한다는 점에서 z-score와 다릅니다.
import pandas as pd
def detect_outliers_iqr(df, columns=None, multiplier=1.5):
numeric = df.select_dtypes(include='number')
if columns:
numeric = numeric[columns]
outlier_report = {}
for col in numeric.columns:
q1 = numeric[col].quantile(0.25)
q3 = numeric[col].quantile(0.75)
iqr = q3 - q1
lower = q1 - multiplier * iqr
upper = q3 + multiplier * iqr
outliers = numeric[(numeric[col] < lower) | (numeric[col] > upper)][col]
outlier_report[col] = {
'q1': round(q1, 3),
'q3': round(q3, 3),
'iqr': round(iqr, 3),
'lower_bound': round(lower, 3),
'upper_bound': round(upper, 3),
'outlier_count': len(outliers),
'outlier_pct': round(len(outliers) / len(df) * 100, 1),
'outlier_values': outliers.tolist()[:10] # first 10
}
return outlier_report분포 유형 식별
분포 유형(정규분포, 왜곡 분포, 쌍봉 분포, 균등 분포)을 식별하면 에이전트가 적절한 통계 검정을 선택하고 데이터를 정확하게 설명하는 데 도움이 됩니다.
정식 검정을 실행하기 전에 왜도와 첨도를 빠른 경험적 지표로 사용합니다.
import pandas as pd
from scipy import stats
def identify_distribution(series):
'''Classify distribution type using skewness, kurtosis, and normality test.'''
clean = series.dropna()
if len(clean) < 8:
return {'type': 'insufficient_data'}
skewness = clean.skew()
kurtosis = clean.kurtosis()
# Shapiro-Wilk normality test (reliable up to ~5000 samples)
sample = clean.sample(min(500, len(clean)), random_state=42)
_, p_value = stats.shapiro(sample)
distribution = 'normal' if p_value > 0.05 else 'non-normal'
if abs(skewness) < 0.5 and p_value > 0.05:
dist_type = 'normal'
elif skewness > 1.0:
dist_type = 'right-skewed (long right tail)'
elif skewness < -1.0:
dist_type = 'left-skewed (long left tail)'
elif abs(skewness) < 0.5 and kurtosis < -1:
dist_type = 'uniform-like'
else:
dist_type = 'approximately normal'
return {
'type': dist_type,
'skewness': round(skewness, 3),
'kurtosis': round(kurtosis, 3),
'normality_pvalue': round(p_value, 4),
'is_normal': p_value > 0.05
}정규성 검정
여러 가지 정식 정규성 검정을 사용할 수 있습니다. Shapiro-Wilk 검정은 작은 표본에, D'Agostino-Pearson 검정은 더 큰 데이터셋에 적합합니다. p값의 기준은 일반적으로 0.05이며, p < 0.05이면 정규성을 기각합니다.
from scipy import stats
import numpy as np
def test_normality(series, alpha=0.05):
clean = series.dropna().values
n = len(clean)
results = {}
# Shapiro-Wilk (best for n < 5000)
if n <= 5000:
stat, p = stats.shapiro(clean)
results['shapiro_wilk'] = {
'statistic': round(stat, 4),
'p_value': round(p, 4),
'is_normal': p > alpha
}
# D'Agostino-Pearson (n >= 20)
if n >= 20:
stat, p = stats.normaltest(clean)
results['dagostino_pearson'] = {
'statistic': round(stat, 4),
'p_value': round(p, 4),
'is_normal': p > alpha
}
# Kolmogorov-Smirnov
mean, std = np.mean(clean), np.std(clean)
stat, p = stats.kstest(clean, 'norm', args=(mean, std))
results['kolmogorov_smirnov'] = {
'statistic': round(stat, 4),
'p_value': round(p, 4),
'is_normal': p > alpha
}
return results전체 통계 프로필
모든 통계 분석을 하나의 full_profile() 함수로 결합하여 데이터프레임의 각 수치 열에 대한 종합적인 통계 요약을 반환하도록 합니다.
def full_statistical_profile(df):
numeric = df.select_dtypes(include='number')
profiles = {}
for col in numeric.columns:
series = numeric[col].dropna()
profile = {
'count': len(series),
'null_count': df[col].isnull().sum(),
'mean': round(series.mean(), 4),
'median': round(series.median(), 4),
'std': round(series.std(), 4),
'min': round(series.min(), 4),
'max': round(series.max(), 4),
'range': round(series.max() - series.min(), 4),
'q1': round(series.quantile(0.25), 4),
'q3': round(series.quantile(0.75), 4)
}
profile['distribution'] = identify_distribution(series)
outliers = detect_outliers_iqr(df, columns=[col])
profile['outliers'] = outliers.get(col, {})
profiles[col] = profile
return {
'profiles': profiles,
'correlations': find_strong_correlations(df),
'shape': {'rows': len(df), 'columns': len(df.columns)}
}자동 통찰 생성
통계 프로필을 LLM에 전달하고 알기 쉬운 언어로 통찰을 생성하도록 요청합니다. 모델은 패턴을 식별하고, 이상 징후를 표시하며, 비즈니스 사용자가 중요하게 여길 만한 결과를 찾아냅니다.
import json
INSIGHT_PROMPT = '''You are a data analyst. Generate 3-5 key insights from this statistical summary.
Dataset: {dataset_name}
Statistical profile:
{profile_json}
For each insight:
- Be specific (use actual numbers)
- Focus on business relevance
- Flag any data quality concerns (high null counts, extreme outliers)
- Note unexpected patterns
Format as bullet points.'''
def generate_insights(df, dataset_name='dataset'):
profile = full_statistical_profile(df)
profile_text = json.dumps(profile, indent=2, default=str)[:3000]
return llm_call(INSIGHT_PROMPT.format(
dataset_name=dataset_name,
profile_json=profile_text
))
# Example output:
# - Revenue column has 3.2% outliers; max value ($48,500) is 12x the median ($3,900)
# - Customer age follows a right-skewed distribution (skewness: 1.4) with most users under 35
# - Strong positive correlation (r=0.87) between session_count and lifetime_value시계열 추세 탐지
시계열 데이터에서는 선형 회귀를 사용하여 전반적인 추세(증가, 감소, 보합)를 탐지합니다. 이를 통해 에이전트가 “매출이 매달 2,400달러씩 증가하고 있습니다.”라고 말할 수 있습니다.
import numpy as np
from scipy import stats
def detect_trend(values):
if len(values) < 3:
return {'trend': 'insufficient_data'}
x = np.arange(len(values))
y = np.array(values, dtype=float)
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
if p_value > 0.05:
trend = 'flat (no significant trend)'
elif slope > 0:
trend = 'increasing'
else:
trend = 'decreasing'
return {
'trend': trend,
'slope_per_period': round(slope, 4),
'r_squared': round(r_value ** 2, 4),
'p_value': round(p_value, 4),
'significant': p_value < 0.05
}
# Example: monthly revenue trend
monthly_revenue = [10000, 11200, 10800, 12500, 13100, 14200, 15000]
print(detect_trend(monthly_revenue))
# {'trend': 'increasing', 'slope_per_period': 834.2, 'r_squared': 0.95, ...}비교 통계
가장 유용한 통찰은 그룹을 비교하는 데서 나오는 경우가 많습니다. “세그먼트 A의 평균 주문 금액은 세그먼트 B보다 40% 높습니다.” 그룹을 비교할 때는 t-검정 또는 Mann-Whitney 검정을 사용합니다.
from scipy import stats
import pandas as pd
def compare_groups(df, group_column, value_column):
groups = df.groupby(group_column)[value_column].apply(list)
group_names = list(groups.index)
comparison = []
for i, g1 in enumerate(group_names):
for j, g2 in enumerate(group_names):
if j <= i:
continue
a, b = groups[g1], groups[g2]
mean_a = pd.Series(a).mean()
mean_b = pd.Series(b).mean()
# Mann-Whitney U (non-parametric, no normality assumption)
stat, p = stats.mannwhitneyu(a, b, alternative='two-sided')
pct_diff = (mean_a - mean_b) / mean_b * 100 if mean_b != 0 else 0
comparison.append({
'group_a': g1, 'group_b': g2,
'mean_a': round(mean_a, 2),
'mean_b': round(mean_b, 2),
'pct_difference': round(pct_diff, 1),
'p_value': round(p, 4),
'significant': p < 0.05
})
return comparison결측값 분석
통계를 계산하기 전에 결측값을 분석합니다. 열의 결측값 비율이 높으면 해당 열에서 계산한 통계가 유효하지 않을 수 있습니다. 결측값 개수와 비율, 패턴(결측값이 무작위인지 체계적인지)을 보고합니다.
import pandas as pd
import numpy as np
def analyze_missing_values(df):
total_rows = len(df)
missing_report = {}
for col in df.columns:
null_count = df[col].isnull().sum()
if null_count == 0:
continue
null_pct = null_count / total_rows * 100
# Check if nulls correlate with another column (systematic pattern)
pattern = 'random'
if null_pct > 5:
for other_col in df.select_dtypes(include='object').columns:
if other_col == col:
continue
null_rates = df.groupby(other_col)[col].apply(
lambda x: x.isnull().mean()
)
if null_rates.max() - null_rates.min() > 0.3: # 30% difference
pattern = f'correlated_with_{other_col}'
break
missing_report[col] = {
'null_count': int(null_count),
'null_pct': round(null_pct, 1),
'severity': 'high' if null_pct > 20 else 'medium' if null_pct > 5 else 'low',
'pattern': pattern
}
return missing_report지식 확인
에이전트 애플리케이션에서 이상치를 탐지할 때 z-score보다 IQR 방법을 선호하는 이유는 무엇입니까?
요약: 통계 요약 에이전트
통계 요약 에이전트는 기준 통계를 위한 df.describe(), 관계 탐색을 위한 상관관계 행렬, 극단값에 강건한 IQR 이상치 탐지, 왜도와 정규성 검정을 통한 분포 식별, 선형 회귀를 통한 추세 탐지를 결합합니다.
자동 통찰 생성을 위해 통계 프로필을 LLM에 전달하면 숫자를 알기 쉬운 언어의 비즈니스 결과로 변환할 수 있습니다. 비교 통계(유의성 검정을 포함한 그룹 비교)는 실행 가능한 통찰을 찾아내는 데 도움이 됩니다.
자주 묻는 질문
“통계 요약 에이전트” 강의는 무료인가요?
네 — “통계 요약 에이전트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
“통계 요약 에이전트”에서 뭘 배우나요?
에이전트가 생성한 보고서에서 분포 분석, 상관관계, 이상치 탐지를 수행합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“통계 요약 에이전트” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.