반응형
단원별 심화 연습 문제¶
In [1]:
!pip install seaborn==0.13.0
Defaulting to user installation because normal site-packages is not writeable Collecting seaborn==0.13.0 Downloading seaborn-0.13.0-py3-none-any.whl (294 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 294.6/294.6 kB 6.1 MB/s eta 0:00:00a 0:00:01 Requirement already satisfied: numpy!=1.24.0,>=1.20 in ./.local/lib/python3.9/site-packages (from seaborn==0.13.0) (1.23.3) Requirement already satisfied: matplotlib!=3.6.1,>=3.3 in ./.local/lib/python3.9/site-packages (from seaborn==0.13.0) (3.6.0) Requirement already satisfied: pandas>=1.2 in ./.local/lib/python3.9/site-packages (from seaborn==0.13.0) (1.4.2) Requirement already satisfied: pillow>=6.2.0 in ./.local/lib/python3.9/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn==0.13.0) (9.3.0) Requirement already satisfied: pyparsing>=2.2.1 in ./.local/lib/python3.9/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn==0.13.0) (3.0.9) Requirement already satisfied: python-dateutil>=2.7 in ./.local/lib/python3.9/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn==0.13.0) (2.8.2) Requirement already satisfied: fonttools>=4.22.0 in ./.local/lib/python3.9/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn==0.13.0) (4.38.0) Requirement already satisfied: cycler>=0.10 in ./.local/lib/python3.9/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn==0.13.0) (0.11.0) Requirement already satisfied: packaging>=20.0 in ./.local/lib/python3.9/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn==0.13.0) (21.3) Requirement already satisfied: kiwisolver>=1.0.1 in ./.local/lib/python3.9/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn==0.13.0) (1.4.4) Requirement already satisfied: contourpy>=1.0.1 in ./.local/lib/python3.9/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn==0.13.0) (1.0.6) Requirement already satisfied: pytz>=2020.1 in ./.local/lib/python3.9/site-packages (from pandas>=1.2->seaborn==0.13.0) (2022.5) Requirement already satisfied: six>=1.5 in ./.local/lib/python3.9/site-packages (from python-dateutil>=2.7->matplotlib!=3.6.1,>=3.3->seaborn==0.13.0) (1.16.0) Installing collected packages: seaborn Attempting uninstall: seaborn Found existing installation: seaborn 0.12.0 Uninstalling seaborn-0.12.0: Successfully uninstalled seaborn-0.12.0 Successfully installed seaborn-0.13.0 [notice] A new release of pip available: 22.2.2 -> 24.1.1 [notice] To update, run: pip install --upgrade pip
In [2]:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import seaborn as sns
import glob
import os
# set floating point formatting
pd.options.display.float_format = '{:,.1f}'.format
root_dir = '/mnt/elice/dataset/restaurant'
Q5¶
In [3]:
sorted(glob.glob(os.path.join(root_dir, "*")))
Out[3]:
['/mnt/elice/dataset/restaurant/chefmozaccepts.csv', '/mnt/elice/dataset/restaurant/chefmozcuisine.csv', '/mnt/elice/dataset/restaurant/chefmozhours4.csv', '/mnt/elice/dataset/restaurant/chefmozparking.csv', '/mnt/elice/dataset/restaurant/geoplaces2.csv', '/mnt/elice/dataset/restaurant/rating_final.csv', '/mnt/elice/dataset/restaurant/usercuisine.csv', '/mnt/elice/dataset/restaurant/userpayment.csv', '/mnt/elice/dataset/restaurant/userprofile.csv']
Restaurants
- chefmozaccepts.csv
- chefmozcuisine.csv
- chefmozhours4.csv
- chefmozparking.csv
- geoplaces2.csv
Consumers
- usercuisine.csv
- userpayment.csv
- userprofile.csv
User-Item Rating
- rating_final.csv
다음을 수행해 주세요.
- 아래 2개의 데이터를 병합 합니다.
- 병합한 후
smoking_area
를 기준으로 그룹하여price
에 대한 데이터 분포(value_counts)를 확인합니다. - 결과를 아래와 같은 데이터프레임 형식으로 출력합니다.
In [51]:
# 데이터셋
chefmozaccepts = pd.read_csv(os.path.join(root_dir, 'chefmozaccepts.csv'))
geoplaces2 = pd.read_csv(os.path.join(root_dir, 'geoplaces2.csv'))
In [54]:
# 코드를 입력해 주세요
# 두 데이터프레임을 'placeID'를 기준으로 병합
merged_df = pd.merge(geoplaces2, chefmozaccepts, on='placeID', how='inner')
# smoking_area를 기준으로 그룹화하고 price에 대한 데이터 분포 계산
price_distribution = merged_df.groupby('smoking_area')['price'].value_counts().reset_index(name='values')
price_distribution
Out[54]:
smoking_area | price | values | |
---|---|---|---|
0 | none | medium | 61 |
1 | none | high | 35 |
2 | none | low | 24 |
3 | not permitted | medium | 32 |
4 | not permitted | low | 13 |
5 | only at bar | medium | 4 |
6 | permitted | medium | 9 |
7 | permitted | low | 5 |
8 | section | high | 47 |
9 | section | medium | 19 |
10 | section | low | 4 |
[출력 결과]
smoking_area | price | values | |
---|---|---|---|
0 | none | medium | 61 |
1 | none | high | 35 |
2 | none | low | 24 |
3 | not permitted | medium | 32 |
4 | not permitted | low | 13 |
5 | only at bar | medium | 4 |
6 | permitted | medium | 9 |
7 | permitted | low | 5 |
8 | section | high | 47 |
9 | section | medium | 19 |
10 | section | low | 4 |
userprofile.csv
와 rating_final.csv
을 활용하여 다음을 산출해 주세요
rating_final.csv
와userprofile.csv
을 병합 후birth_year
기준으로 1980년 이상 1989년 이하 출생(1980년대 출생자)자를 필터 후rating
의 평균과 표준편차를 산출해 주세요
In [12]:
# 데이터셋
userprofile = pd.read_csv(os.path.join(root_dir, 'userprofile.csv'))
rating_final = pd.read_csv(os.path.join(root_dir, 'rating_final.csv'))
In [17]:
# 코드를 입력해 주세요
# 데이터셋 병합 (공통 컬럼을 기준으로 병합)
merged_df = pd.merge(rating_final, userprofile, on='userID')
# 1980년 이상 1989년 이하 출생자 필터링
filtered_df = merged_df[(merged_df['birth_year'] >= 1980) & (merged_df['birth_year'] <= 1989)]
# rating의 평균과 표준편차 계산
filtered_df['rating'].mean()
filtered_df['rating'].std()
# 결과 출력
print("mean:rating_mean}")
print("std: {rating_std}")
mean: {rating_mean} std: {rating_std}
[출력 결과]
mean 1.1 std 0.8 Name: rating, dtype: float64
userprofile.csv
, rating_final.csv
, geoplaces2.csv
3개의 데이터를 활용하여 다음을 산출해 주세요
- 3개의 데이터를
userID
와placeID
를 기준으로 병합하여 하나의 데이터프레임 형태로 만듭니다.
[병합 가이드라인]
userprofile.csv
와rating_final.csv
은userID
를 기준으로inner
병합합니다.- 이전에 병합한 데이터프레임과
geoplaces2.csv
를 병합한 데이터프레임을 기준으로left
병합합니다. 병합할 때 공통된 키값이 있을 경우on='placeID
를 지정합니다. - 예시)
pd.merge(df1, df2, how='left', on='placeID')
조건필터링
- 병합된 데이터프레임에서
drink_level
컬럼의 데이터가social drinker
인 기준으로 필터 후city
별rating
의 평균을 도출해 냅니다. - 결과는 내림차순 정렬하여 출력합니다.
In [ ]:
# 데이터셋
userprofile = pd.read_csv(os.path.join(root_dir, 'userprofile.csv'))
rating_final = pd.read_csv(os.path.join(root_dir, 'rating_final.csv'))
geoplaces2 = pd.read_csv(os.path.join(root_dir, 'geoplaces2.csv'))
In [32]:
# 코드를 입력해 주세요
# userprofile.csv와 rating_final.csv를 userID를 기준으로 inner 병합
merged_df1 = pd.merge(userprofile, rating_final, on='userID')
# 이전에 병합한 데이터프레임과 geoplaces2.csv를 placeID를 기준으로 left 병합
merged_df = pd.merge(merged_df1, geoplaces2, on='placeID', how='left')
# drink_level이 'social drinker'인 데이터를 필터링
filtered_df = merged_df[merged_df['drink_level'] == 'social drinker']
# city 별 rating의 평균을 계산
city_rating_mean = filtered_df.groupby('city')['rating'].mean().reset_index()
# 결과를 내림차순으로 정렬
result_df = city_rating_mean.sort_values(by='rating', ascending=False)
result_df
Out[32]:
city | rating | |
---|---|---|
4 | Jiutepec | 2.0 |
7 | cuernavaca | 2.0 |
10 | san luis potos | 2.0 |
9 | s.l.p. | 1.5 |
0 | ? | 1.4 |
5 | San Luis Potosi | 1.3 |
11 | san luis potosi | 1.3 |
12 | san luis potosi | 1.2 |
13 | slp | 1.2 |
3 | Cuernavaca | 1.2 |
14 | victoria | 1.1 |
2 | Ciudad Victoria | 1.0 |
6 | Soledad | 1.0 |
8 | s.l.p | 1.0 |
1 | Cd Victoria | 0.0 |
[출력 결과]
city | rating | |
---|---|---|
0 | Jiutepec | 2.0 |
1 | cuernavaca | 2.0 |
2 | san luis potos | 2.0 |
3 | s.l.p. | 1.5 |
4 | ? | 1.4 |
5 | San Luis Potosi | 1.3 |
6 | san luis potosi | 1.3 |
7 | san luis potosi | 1.2 |
8 | slp | 1.2 |
9 | Cuernavaca | 1.2 |
10 | victoria | 1.1 |
11 | Ciudad Victoria | 1.0 |
12 | Soledad | 1.0 |
13 | s.l.p | 1.0 |
14 | Cd Victoria | 0.0 |
제출¶
제출을 위해 아래에 새로 불러온 chefmozaccepts.csv
와 geoplaces2.csv
데이터에 아래 작업을 수행한 결과를 result_df
에 저장하세요.
- 2개의 데이터를 병합 합니다.
- 병합한 후
smoking_area
를 기준으로 그룹하여price
에 대한 데이터 분포(value_counts)를 구하고 컬럼 이름을values
로 설정합니다. - 위 결과에 인덱스를 초기화하여 데이터프레임 형식으로 저장합니다.
In [55]:
chefmozaccepts = pd.read_csv(os.path.join(root_dir, 'chefmozaccepts.csv'))
geoplaces2 = pd.read_csv(os.path.join(root_dir, 'geoplaces2.csv'))
# 두 데이터프레임을 'placeID'를 기준으로 병합
merged_df = pd.merge(geoplaces2, chefmozaccepts, on='placeID', how='inner')
# smoking_area를 기준으로 그룹화하고 price에 대한 데이터 분포 계산
result_df = merged_df.groupby('smoking_area')['price'].value_counts().reset_index(name='values')
result_df
Out[55]:
smoking_area | price | values | |
---|---|---|---|
0 | none | medium | 61 |
1 | none | high | 35 |
2 | none | low | 24 |
3 | not permitted | medium | 32 |
4 | not permitted | low | 13 |
5 | only at bar | medium | 4 |
6 | permitted | medium | 9 |
7 | permitted | low | 5 |
8 | section | high | 47 |
9 | section | medium | 19 |
10 | section | low | 4 |
반응형
'Biusiness Insight > Data Science' 카테고리의 다른 글
[Python] Matplotlib을 활용한 시각화 (0) | 2024.06.30 |
---|---|
[Python] 데이터프레임 시각화 (0) | 2024.06.30 |
[Python] Pandas concat, merge (0) | 2024.06.30 |
[Python] Pandas groupby, pivottable 실습 (0) | 2024.06.30 |
[Python] Pandas 고급 전처리와 피벗테이블 (0) | 2024.06.30 |