본문 바로가기

Python

[Python] Correlation & Heatmap

Python에서 Correlationship 계산 및 시각화

필수 패키지 - pandas, matplotlib, seaborn

 

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

 

file = pd.read_csv('./filename.csv')

file.head()

# column = file.columns

 

corr = file.corr() # pandas에서 dataframe형식에 대해 지원

# corrw = file.corrwith(file["column_name"]) # 특정 column과 다른변수들과의 관계, size = (len(column),)
# corrw = pd.DataFrame(corr) # heatmap그리기 위함, corrw이 Series로 출력되기 때문에 size를 (len(column),1)로 만들어줌

 

plt.figure(figsize=(15,15))

sns.heatmap(data = corr, annot=True, fmt = '.2f' ) # annot : 상관계수 프린팅 fmt = '.2f' : 소숫점 2자리수 까지 표현

 

*다른 컬러맵 설정 (Colormap Family) matplotlib.org/3.2.1/tutorials/colors/colormaps.html