본문 바로가기
study/Python

[Python] 43. chipotle.tsv 파일 분석하기, drink.csv 파일 분석하기. 상관계수

by 금이패런츠 2022. 7. 4.
728x90
반응형

1. chipotle.tsv 파일 분석하기

2. drink.csv 파일 분석하기. 상관계수

# -*- coding: utf-8 -*-
"""
Created on Mon Jul  4 09:26:52 2022

@author: p011v
"""

########## 1. chipotle.tsv 파일 분석하기

import pandas as pd
import matplotlib.pyplot as plt
chipo = pd.read_csv("data/chipotle.tsv", sep = '\t')
chipo.describe()

# order_id 컬럼의 자료형을 문자형으로 변경하기
chipo["order_id"] = chipo["order_id"].astype(str)
chipo.describe()
chipo.head()
chipo.info()

# item_price 컬럼의 자료형을 실수형으로 변경하기
# 1. 기존의 함수이용하여 자료형으로 변경 (str.replace())
chipo["item_price"] = chipo["item_price"].str.replace("$", "").astype(float)

# 2. apply함수 : 요소들에 적용되는 함수지정.  apply(함수이름 | 람다식)
# flambda x : float(x[1:]) : 1번($) 이후 float로 변경
#             x : 요소 하나의 값. ex) $12.5                          
#  float(x[1:]) : x값의 두번째 이후 부분을 실수형으로 변환. 요소를 채움.     
chipo["item_price"] = chipo["item_price"].apply(lambda x : float(x[1:]))
chipo.info()

# 주문금액 합계
chipo.describe()
chipo["item_price"].sum()

'''
    주문당 평균 주문금액 조회하기
        주문번호  주문금액
           1         1
           1         3
           2         1
           2         1
           
           전체주문금액 : 6
           주문건수 : 2
           주문당 평균금액 : 3
'''
# 1.
# 전체주문금액
hap = chipo["item_price"].sum()
hap
# 주문건수
cnt = len(chipo.groupby("order_id")["item_price"].count())
cnt
# 주문당 평균금액
hap / cnt

# 2.
# 주문당 평균금액
chipo.groupby("order_id")["item_price"].sum().mean()

'''
    한번의 주문시 주문금액이 50달러 이상인 주문id 출력하기
      1     25
      1     30
      2     2
      2     3
      2     30
      
     주문시 주문금액 50달러 이상인 주문id : 1
'''
order_id_tot = chipo.groupby("order_id").sum()
result = order_id_tot[order_id_tot["item_price"] >= 50]
result

print("50달러 이상 주문 번호 : ", result.index.values)
print("50달러 이상 주문 건수 : ", len(result.index.values))
print("50달러 이상 주문 비율 : ", len(result.index.values) / len(order_id_tot) * 100)

#  한번의 주문시 주문금액이 50달러 이상인 주문정보 출력하기
pd.set_option("display.max_columns", 5)
chipo_50 = chipo.loc[chipo["order_id"].isin(result.index.values)]
chipo_50.info()
chipo_50.head(10)

'''
    item_name 별 단가를 조회하기
'''
# item_name 별 최소값
price_one = chipo.groupby("item_name").min()["item_price"]
price_one #단가

# 단가의 분포를 히스토그램으로 출력하기
import matplotlib.pyplot as plt
plt.hist(price_one)
plt.ylabel("counts")
plt.title("Histogram of item price")
           
# 단가가 높은 item 10개 출력하기
price_one.sort_values(ascending=False)
price_one.sort_values(ascending=False)[:10]

# 주문당 판매금액이 높은 상위 5건 주문의 총수량을 조회하기
price5 = chipo.groupby("order_id").sum().sort_values(by="item_price", ascending=False)[:5]
price5
price5["quantity"].sum()
# 주문당 판매금액이 높은 상위 5건 주문의 정보 조회하기
pd.set_option("display.max_columns", 5) #컬럼 5개를 조회
pd.set_option("display.max_rows", None) #모든 레코드 조회
chipo_5 = chipo.loc[chipo["order_id"].isin(price5.index.values)]
chipo_5[["order_id", "item_name", "quantity"]]

# Veggie Salad Bowl 몇번 주문되었는지 출력하기
'''
    주문번호       상품명
       1      Veggie Salad Bowl
       2      Veggie Salad Bowl
       2      Veggie Salad Bowl
       
       => 2
'''
chipo_salad = chipo[chipo["item_name"] == 'Veggie Salad Bowl']
len(chipo_salad)
len(chipo_salad.groupby("order_id").sum())

# 한 주문 내에서 중복 집계된 item_name을 제거합니다.
chipo_salad = chipo_salad.drop_duplicates(['item_name', 'order_id'])
print(len(chipo_salad))

########## 2. drink.csv 파일 분석하기. 상관계수
# 전세계 음주 데이터 분석하기 : drink.csv 파일 분석
# 컬럼 = 변수 = 피처
import pandas as pd
drinks = pd.read_csv("data/drinks.csv")
drinks.info()
'''
    country : 국가명
    beer_servings : 맥주소비량
    spirit_servings : 음료소비량
    wine_servings : 와인소비량
    total_litres_of_pure_alcohol : 순수 알콜소비량
    continent : 대륙명
'''
# 맥주, 와인 상관관계 조회
'''
    상관계수 : 
        pearson (피어슨) : 기본. 연속형 변수와 변수간의 선형관계 확인을 위한 상관계수
                          단, 두 변수 모두 정규형 데이터야아 함. 
        kendall (켄달) :  샘플사이즈가 작은경우, 동률데이터의 확률이 높을때 사용되는 상관계수
        spearman (스피어만) : 정규화되지 않은 경우에 사용되는 상관계수
'''
beer_wine_corr = drinks[["beer_servings", "wine_servings"]].corr(method="pearson")
beer_wine_corr

beer_wine_corr = drinks[["beer_servings", "wine_servings"]].corr(method="kendall")
beer_wine_corr

beer_wine_corr = drinks[["beer_servings", "wine_servings"]].corr(method="spearman")
beer_wine_corr

# 맥주, 와인, spirit, alcohol 상관계수 조회하기
cols = drinks.columns[1:-1]
corr = drinks[cols].corr()
corr

# 상관계수 시각화하기
# seaborn 히트맵을 이용하여 시각화하기
import matplotlib.pyplot as plt
import seaborn as sns
cols_view = ["beer", "spirit", "wine", "alcohol"] #그래프의 구분사용할 컬럼명
sns.set(font_scale=1.5)                 #글자크기 지정
hm = sns.heatmap(corr.values,           #데이터 값
                 cbar=True,             #색상바 출력
                 annot=True,            #데이터값 표시
                 square=True,           #히트맵 모양을 사각형으로 표현
                 fmt=".2f",             #데이터값 출력시  소숫점이하 2자리까지
                 annot_kws={"size":15}, #데이터값 글자크기 지정
                 yticklabels=cols_view, #y축의 라벨
                 xticklabels=cols_view  #x축의 라벨
                 )

# seaborn 모듈의 산점도를 이용하여 시각화하기
sns.pairplot(drinks[cols], height=2.5)
plt.show()
drinks.head()
sns.regplot(x="beer_servings", y="total_litres_of_pure_alcohol", data=drinks)

# 각 변수의 결측값 갯수 조회하기
drinks.isnull().sum()
# 대륙별 국가수를 조회하기
drinks["continent"].value_counts() #갯수의 내림차순정렬
drinks.groupby("continent").count()["country"] #continent 오름차순 정렬

# 대륙정보의 결측데이터를 "OT" 문자열로 변경하기
# fillna 함수 : 결측값을 다른 값으로 치환
drinks['continent'] = drinks['continent'].fillna('OT')
drinks.info()
drinks['continent'].value_counts()
#대륙별 국가의 갯수를 파이 그래프로 출력하기
labels = drinks['continent'].value_counts().index.tolist()
explode = (0, 0, 0, 0.5, 0, 0) #조각을 밖으로 표시, 0.5 (50% 정도 밖으로 표시되게 해줌.)
plt.pie(drinks['continent'].value_counts(), labels=labels,\
        autopct='%.0f%%', explode=explode, shadow=True)
plt.title('null data to \'OT\'')

# 대륙별 spirit_servings의 평균, 최소, 최대, 합계를 출력
drinks.groupby('continent').mean()['spirit_servings']
drinks.groupby('continent').min()['spirit_servings']
drinks.groupby('continent').max()['spirit_servings']
drinks.groupby('continent').sum()['spirit_servings']

drinks.groupby('continent')['spirit_servings'].mean()
drinks.groupby('continent')['spirit_servings'].min()
drinks.groupby('continent')['spirit_servings'].max()
drinks.groupby('continent')['spirit_servings'].sum()

drinks.groupby('continent').spirit_servings.mean()
drinks.groupby('continent').spirit_servings.min()
drinks.groupby('continent').spirit_servings.max()
drinks.groupby('continent').spirit_servings.sum()

# 한꺼번에 조회
drinks.groupby('continent').spirit_servings.agg(['mean','min','max','sum'])

# total_liters_of_pure_alcohol : 알콜량
# 대륙별 알콜량의 평균이 전체 알콜량 평균보다 많은 대륙을 조회하기
# 1. 전체알콜량 평균
total_mean = drinks.total_litres_of_pure_alcohol.mean()
total_mean
# 2. 대륙별 알콜량 평균
continent_mean = drinks.groupby("continent")["total_litres_of_pure_alcohol"].mean()
continent_mean
type(continent_mean)
# 3. 전체 알콜량 평균보다 많은 평균을 가진 대륙
continent_mean_over = continent_mean[continent_mean > total_mean]
continent_mean_over
list(continent_mean_over.index)

# 대륙별 beer_servings이 평균이 가장 많은 대륙 조회하기
drinks.groupby("continent").beer_servings.mean()
drinks.groupby("continent").beer_servings.mean().idxmax()

# 대륙별 beer_servings이 평균이 가장 적은 대륙 조회하기
drinks.groupby("continent").beer_servings.mean().idxmin()

'''
    대륙별 total_litres_of_pure_alcohol 섭취량 평균 시각화 하기
'''
import numpy as np
# 대륙별 알콜 섭취량 평균
continent_mean = drinks.groupby("continent")["total_litres_of_pure_alcohol"].mean()
continent_mean
# 전체평균
total_mean

continents = continent_mean.index.tolist() #대륙목록 리스트
continents.append("Mean") #Mean 추가
continents
x_pos = np.arange(len(continents)) # 0 ~ 6까지의 정수값. 배열 7개를 생성
alcohol = continent_mean.tolist()
alcohol
alcohol.append(total_mean) #전체 평균값 추가
# plt.bar : 막대그래프
# bar_list : 막대그래프에서 막대 목록
bar_list = plt.bar(x_pos, alcohol, align='center', alpha=0.5)
# bar_list[7-1] : 마지막 막대 그래프
# set_color('r') : 색상 설정. r:빨강색. red
bar_list[len(continents) - 1].set_color('r')
# plt.plot : 선그래프
# x축의 값 : 0, 6
# y축의 값 : total_mean, total_mean
# "k--" : k(검정), --(점선)
plt.plot([0., 6], [total_mean, total_mean],'k--')
plt.xticks(x_pos, continents) # x축의 값을 contienet로 변경
plt.ylabel('total_litres_of_pure_alcohol') #y축 설명
plt.title('total_litres_of_pure_alcohol by Continent') #제목
plt.show()

'''
    대륙별 beer_servings의 평균을 막대그래프로 시각화
    가장 많은 맥주를 소비하는 대륙(EU)의 막대의 색상을 빨강색으로 변경하기
    전체 맥주 소비량 평균을 구해서 막대그래프에 추가
    평균선을 출력하기. 막대 색상은 노랑색
    평균선은 검정색("k--")
'''
import numpy as np
beer_mean = drinks.groupby("continent")["beer_servings"].mean() #대륙별 평균 맥주소비량
beer_mean
total_mean = drinks.beer_servings.mean()
total_mean
continents = beer_mean.index.tolist() #대륙목록 리스트
continents.append("Mean") #Mean 추가
x_pos = np.arange(len(continents)) # 0 ~ 6까지의 정수값. 배열 7개를 생성
beer = beer_mean.tolist() #대륙별 맥주 소비량 평균값
beer.append(total_mean) #전체 평균값 추가
beer
beer_mean.idxmax() #최대 맥주 소비량 대륙 인덱스
beer_mean.argmax() #최대 맥주 소비량 대륙 인덱스 순서
continents.index("Mean") #continent 리스트에서 "Mean" 값의 위치값 리턴
#bar_list : 막대 목록
bar_list = plt.bar(x_pos, alcohol, align='center', alpha=0.5) #막대그래프 출력
bar_list[beer_mean.argmax()].set_color('r')
bar_list[continents.index("Mean")].set_color('y')
plt.xticks(x_pos, continents) # x축의 값을 contienet로 변경
plt.plot([0., 6], [total_mean, total_mean],'k--')
plt.ylabel('beer_servings') #y축 설명
plt.title('beer_servings by Continent') #제목
plt.show()

########## 3. 
# 대한민국은 얼마나 술을 독하게 마시는 나라일까?
# total_servings 피처 생성
# total_servings : 모든 소비량의 합
drinks["total_servings"] = \
    drinks["beer_servings"] +drinks["spirit_servings"] + drinks["wine_servings"]
drinks.info()
drinks.head()
# alcohol_rate = 알콜소비량/총소비량 : 알콜비율
drinks["alcohol_rate"] = drinks["total_litres_of_pure_alcohol"]/drinks["total_servings"]
drinks.info()
# alcohol_rate 컬럼의 값이 결측값 : drinks["total_servings"]이 0인 경우 불능 => 결측값
# drinks 데이터중 alcohol_rate 컬럼이 결측값인 레코드
drinks[drinks['alcohol_rate'].isnull()]
# alcohol_rate컬럼이 결측값인 경우 0으로 채우기
drinks['alcohol_rate'] = drinks['alcohol_rate'].fillna(0)
drinks.info()
# drinks 데이터의 country, alcohol_rate 컬럼만을 가지는 데이터 country_alcohol_rank에 저장
country_alcohol_rank = drinks[["country", "alcohol_rate"]]
country_alcohol_rank
# country_alcohol_rank 알콜 비율의 내림차순으로 정렬
country_alcohol_rank = country_alcohol_rank.sort_values(by=["alcohol_rate"], ascending=False)
country_alcohol_rank
country_alcohol_rank.head()
country_alcohol_rank.tail()
# South Korea의 위치값 출력하기
country_alcohol_rank.head(20)
country_alcohol_rank.country.tolist().index("South Korea") #14. 15번째로 알콜비율이 높다.
728x90
반응형