import platform
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
%matplotlib inline
path = "C:/Windows/Fonts/malgun.ttf"
if platform.system() == "Darwin":
rc("font", family="Arial Unicode MS")
elif platform.system() == "Windows":
font_name = font_manager.FontProperties(fname=path).get_name()
rc("font", family=font_name)
else :
print("Unknown system. sorry")
# 마이너스 부호 때문에 한글이 깨질 수 있어 주는 설정
plt.rcParams["axes.unicode_minus"] = False
# pip install koreanize-matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import koreanize_matplotlib
%matplotlib inline
plt.plot([-1, 0, 1, 2]) # - 부호가 제대로 표기되는지 확인하기 위해 -1 ~ 2 사이 값
plt.rcParams["font.family"] = "NanumGothic"
plt.title('그래프 한글 테스트')
plt.show()
# 1. boxplot
sns.boxplot(iris_pd, x="petal length (cm)", y="species", orient="h");
# 2. pairplot
sns.pairplot(iris_pd);
sns.pairplot(iris_pd, hue='species');
sns.pairplot(iris_pd, vars=['petal length (cm)','petal width (cm)'], hue='species');
# 3. scatterplot
sns.scatterplot(iris_pd, x='petal length (cm)', y='petal width (cm)', hue='species');
# 4. lmplot
sns.lmplot(data, x='Length of Membership', y='Yearly Amount Spent');
# 5. regplot
sns.regplot(x='RM', y='PRICE', data=boston, ax=ax[0])
# 6. countplot
sns.countplot(x='taste', data=wine);
f, ax = plt.subplots(1,2, figsize=(12,5));
ax[1].set_title('Count plot - survived');
sns.countplot(ax=ax[1], data=titanic, x='survived')
sns.countplot(ax=ax[1], data=titanic, x='sex', hue='survived')
# 7. barplot
plt.subplot(131) # 1행 3열의 1번째
sns.barplot(data=titanic, x='pclass', y='survived');
# 8. plotly, histogram
import plotly.express as px
fig = px.histogram(titanic, x='age')
fig = px.histogram(wine, x='quality', color='color')
fig.show()
# 9. pie (%)
titanic['survived'].value_counts().plot.pie(ax=ax[0], autopct='%1.1f%%', explode=[0, 0.05])
ax[0].set_title('Pie plot - survived');
ax[0].set_ylabel('')
# 10. heatmap
# corr_mat = boston.corr().round(1)
sns.heatmap(data=corr_mat, annot=True, cmap='bwr');
# 11. hist
wine.hist(bins=10, figsize=(15,10))
# 딕셔너리로 데이터프레임 만들기
data = {'x':[1,2,3,4,5], 'y':[1,3,4,5,6]}
df = pd.DataFrame(data)
# 1,2,4행 0,2열
df.iloc[[1,2,4], [0,2]]
# E열에 값 추가
df["E"] = ["one","two","three","four"]
# 특정 행 삭제(0번째 행)
pop_Seoul.drop([0], inplace=True)
pop = pop.drop(pop[pop["ID"] == tmp].index)
# 특정컬럼을 인덱스로 지정(구별 컬럼을 인덱스로)
data_result.set_index("구별", inplce=True)
# 컬럼 순서 변경
df = pd.DataFrame(data, columns=["Rank", "Cafe", "Menu", "URL"])
df = df.loc[:, ["Rank","Cafe","Menu","Price","Address"]]
# 값 변경
population.loc[population["구분"] == "총인구수 (명)", "구분"] = "합계"
# 인덱스, 컬럼 레벨
pop[pop["소멸위기지역"] == True].index.get_level_values(1)
pop.columns.get_level_values(0)
# 값이 이 중 (미)포함이면
if row["광역시도"][-3:] not in ["광역시", "특별시", "자치시"]:
if row["시도"] in values:
# 이 중 해당하는 값 있는 행 데이터프레임
test = "|".join(target_country_list)
terror_country10_df = df[df["Country"].str.contains(test)]
# crosstab
pd.crosstab(titanic['pclass'], titanic['survived'], margins=True)
# cut
titanic['age_cut'] = pd.cut(titanic['age'], bins=[0,7,15,30,60,100], include_lowest=True, labels=['baby','teen','young','adult','old'])
# notnull행만 사용
titanic = titanic[titanic['age'].notnull()]
# 데이터프레임 합치기
df = pd.concat([df1, df2])
# 값 개수 확인
wine['quality'].value_counts()
# 리스트
feature_name_list = [each for each in boston.feature_names]
wine['taste'] = [1. if grade>5 else 0. for grade in wine['quality']]
feature_name = feature_name_df.iloc[:,1].values.tolist()
# 소수점 출력
print('recall : {0:.4f}, f1 : {1:.4f}, auc : {2:.4f}'.format(re, f1, auc))