KT AIVLE/Python Syntax

데이터분석_문법정리

bestone888 2024. 10. 6. 18:37

데이터 분석 문법 정리

In [ ]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

import scipy.stats as spst
import random as rd

from statsmodels.graphics.mosaicplot import mosaic

단변량 분석_숫자형

In [ ]:
# 데이터프레임의 전체 변수 기초통계량 조회
df.describe(include = 'all')

# 히스토그램
# bins = 구간 개수, 설정 안하면 auto
plt.hist(df[column], bins = ?, edgcolor = 'color')
sns.histplot(x = ?, data = df, bins = ?)

# 밀도함수(kde)
sns.kdeplot(x = ?, data = df)

# 밀도함수와 히스토그램 동시에 그리기
sns.histplot(x = ?, data = df, kde = True)

# boxplot(.notnull())
plt.boxplot(df)
plt.boxplot(df, vert = False)

sns.boxplot(x = df)
sns.boxplot(y = df)
In [ ]:
 

단변량 분석_범주형

In [ ]:
# 개수 집계
df[column].value_counts()

# 막대그래프: 집계 & 시각화 동시에
sns.countplot(y = ?, data = df)
sns.countplot(x = ?, data = df)
In [ ]:
# pie chart
# 집계된 데이터 입력

plt.pie(df[col], labels=None, colors=None, autopct=None, startangle=None, explode=None, shadow=False, counterclock=True)

# 예시
plt.pie(df.values, labels = df.index, autopct = '%.2f%%')

# autopct: 각 조각의 비율을 소수점 n까지 표기 (%1.2f%%)
# - 소수점 앞 1: 전체 숫자가 차지할 최소 자리 수
# - 소수점 뒤 2: 소수점 2자리까지 표기

# startangle: 시작 각도
# explode: 특정 조각을 중심에서 떨어트림
# shadow: 그림자 추가 여부
# countercolock: 반시계 방향 여부
In [ ]:
 

이변량 분석_숫자vs숫자

In [ ]:
# 산점도
# scatter(.notnull())
plt.scatter(df[x], df[y])

sns.scatterplot(x = ?, y = ?, data = df, hue = ?)

# pairplot: 한번에 모든 변수 시각화
sns.pairplot(df, kind = 'reg')
In [ ]:
# 산점도와 히스토그램 함께 보기
# jointplot
sns.jointplot(x = ?, y = ?, data = df)
In [ ]:
# 상관계수와 p-value
import scipy.stats as spst
spst.pearsonr(df[col1], df[col2])

# 상관계수 한번에 구하기
df.corr()
In [ ]:
# heatmap 시각화
sns.heatmap(df.corr(),
            annot = True,            # 숫자(상관계수) 표기 여부
            fmt = '.3f',             # 숫자 포멧 : 소수점 3자리까지 표기
            cmap = 'RdYlBu_r',       # 칼라맵
            vmin = -1, vmax = 1)     # 값의 최소, 최대값
In [ ]:
 

이변량 분석_범주vs숫자

In [ ]:
# barplot
# 집계되지 않은 데이터 입력

sns.barplot(x = col1, y = col2, data = df)

# boxplot
sns.boxplot(x = col1, y = col2, data = df)

# t-test
# col1의 두가지 범주 (col1_1, col1_2)에 따른 t검정
col1_1 = df.loc[df[col1] == col1_1, col2]
col1_2 = df.loc[df[col1] == col1_2, col2]
spst.ttest_ind(col1_1, col1_2)
In [ ]:
# ANOVA
spst.f_oneway(*columns)


# 반복문으로 f통계
group_list = list()
for group in df[col1].unique:
    g = df.loc[df[col1] == group, col2]
    group_list.append(g)
spst.f_oneway(*group_list)
In [ ]:
# (추가) 조건 필터링
# example) Weekday -> Weekend

# 방법1
df['Weekend'] = 0
df.loc[df['Weekday'].isin(5,6), 'Weekend'] ==1

# 방법2
df['Weekend'] = np.where(df['Weekday']>=5, 1, 0)
In [ ]:
 

이변량 분석_범주vs범주

In [ ]:
from statsmodels.graphics.mosaicplot import mosaic

# 교차표
pd.crosstab(df[col1], df[col2])

# normalize: 'columns', 'index', 'all'
pd.crosstab(df[col1], df[col2], normalize = 'columns')
In [ ]:
# 시각화1: mosaic
mosaic(df, [col1, col2])

# 시각화2: Stacked Bar
# 비율만 비교
df2 = pd.crosstab(df[col1], df[col2], normalize = 'index')
df2.plot.bar(stacked = True)
In [ ]:
# 카이제곱검정
df2 = pd.crosstab(df[col1], df[col2])
spst.chi2_contingency(df2)
In [ ]:
 

이변량 분석_숫자vs범주

In [ ]:
# 히스토그램을 나눠 그림
sns.histplot(x = col1, data = df, hue = col2)

# kde
sns.kdeplot(x = col1, data = df, hue = col2)

# common_norm = False: 각각 아래 면적의 합이 1
# multiple = 'fill': 두 범주의 비율 비교

sns.kdeplot(x = col1, data = df, hue = col2, common_norm = False)
sns.kedplot(x = col1, data = df, hue = col2, multiple = 'fill')

'KT AIVLE > Python Syntax' 카테고리의 다른 글

딥러닝_문법정리  (0) 2025.01.22
머신러닝_지도_문법정리  (0) 2024.11.03
lambda, filter, reduce  (0) 2024.10.06
데이터다듬기_문법정리  (0) 2024.09.29