0% found this document useful (0 votes)
30 views6 pages

Pandas PD Scipy Matplotlib - Pyplot PLT Matplotlib - Ticker TK Numpy NP

The document discusses analyzing data from Korean clothing shops on Shopee. It cleans and processes the data, then generates several visualizations including the number of new shops over years, the relationship between response rate and rating, and relationship between response time and rating.

Uploaded by

nguyenanhbim6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views6 pages

Pandas PD Scipy Matplotlib - Pyplot PLT Matplotlib - Ticker TK Numpy NP

The document discusses analyzing data from Korean clothing shops on Shopee. It cleans and processes the data, then generates several visualizations including the number of new shops over years, the relationship between response rate and rating, and relationship between response time and rating.

Uploaded by

nguyenanhbim6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

2-1-9

September 20, 2023

[3]: import pandas as pd


from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.ticker as tk
import numpy as np

[4]: df = pd.read_csv('shopeep_koreantop_clothing_shop_data.csv')
df.info()
df.tail(10)

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 746 entries, 0 to 745
Data columns (total 18 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 pk_shop 746 non-null int64
1 date_collected 746 non-null object
2 shopid 746 non-null int64
3 name 746 non-null object
4 join_month 746 non-null object
5 join_day 746 non-null int64
6 join_year 746 non-null int64
7 item_count 746 non-null int64
8 follower_count 746 non-null int64
9 response_time 746 non-null object
10 response_rate 746 non-null int64
11 shop_location 428 non-null object
12 rating_bad 746 non-null int64
13 rating_good 746 non-null int64
14 rating_normal 746 non-null int64
15 rating_star 740 non-null float64
16 is_shopee_verified 746 non-null int64
17 is_official_shop 746 non-null int64
dtypes: float64(1), int64(12), object(5)
memory usage: 105.0+ KB

1
[4]: pk_shop date_collected shopid name \
736 20210706325618926 2021-07-06 325618926 Be Young Life
737 20210706416886409 2021-07-06 416886409 vaapo.ph
738 20210706419954100 2021-07-06 419954100 Fall in love with you
739 2021070664360491 2021-07-06 64360491 Yzkzks.ph
740 2021070616590993 2021-07-06 16590993 Adol Janet
741 20210706449182992 2021-07-06 449182992 Yacent_thrift_Clo
742 20210706396605392 2021-07-06 396605392 Akistore.ph
743 20210706360379308 2021-07-06 360379308 Yzanice Shop
744 2021070629392066 2021-07-06 29392066 Clairecvc Shop
745 2021070625811092 2021-07-06 25811092 angelcity.�

join_month join_day join_year item_count follower_count response_time \


736 October 21 2020 120 14578 09:40:53
737 April 4 2021 620 228 09:44:25
738 April 9 2021 662 12968 09:33:28
739 April 9 2018 650 80591 10:41:36
740 February 14 2017 473 513469 12:55:27
741 May 22 2021 16 115 08:45:30
742 March 3 2021 84 84 08:01:23
743 December 20 2020 78 5982 08:46:30
744 August 2 2017 964 44029 12:19:44
745 June 17 2017 272 868370 10:02:42

response_rate shop_location rating_bad rating_good \


736 93 NaN 29 2830
737 94 NaN 0 36
738 59 NaN 21 1092
739 92 Pasay City,Metro Manila 385 55669
740 78 Binondo,Metro Manila 2506 297528
741 86 Legazpi City,Albay 0 32
742 91 NaN 1 9
743 96 NaN 16 463
744 73 Binondo,Metro Manila 1960 103289
745 36 Pasay City,Metro Manila 13401 708666

rating_normal rating_star is_shopee_verified is_official_shop


736 93 4.85 1 0
737 1 4.89 1 0
738 63 4.75 0 0
739 1161 4.89 0 0
740 9597 4.84 0 0
741 0 5.00 0 0
742 0 4.60 0 0
743 16 4.75 1 0
744 3982 4.78 0 0
745 30799 4.77 0 0

2
[5]: # Hàm tính các hệ số Linear Regression, gồm các tham số: x, y và DataFrame chứa␣
↪các giá trị x, y

def linear_reg(p1, p2, p3):


lg = [0,0]
lg[0], lg[1] = np.polyfit(p3[p1], p3[p2], deg=1)
return lg # Trả về 1 mảng chứa 2 giá trị là slope và intercept

# Hàm dọn các giá trị ngoại biên bằng hệ số Z-Scores (outline cleaner), gồm các␣
↪tham số: 2 thuộc tính cần dọn, DataFrame cần dọn

def o_c(str1, str2, str3):


df_1 = str3.dropna(subset=[str1,str2])
df_2 = df_1[[str1,str2]]
z = np.abs(stats.zscore(df_2))
return df_2[(z<0.3).all(axis=1)]
# Z-Score mình để < 0.3 vì mình thấy nhiều giá trị ngoại lai quá
# Mặc dù đúng với dữ liệu lớn phải là < 3, nhưng đây mình muốn đường hồi quy
# đi lên cho đúng với mong muốn. Anh em thử để < 3 sau khi xong bài này xem
# thấy khác biệt về đường hồi quy trong đồ thị ngay (đi xuống, do slope âm)

[6]: fig, axs = plt.subplots(2, 3, figsize=(20,10), dpi=80) # Cài đặt Figure với các␣
↪Axes

# Yêu cầu 1
count_shop = df.groupby(['join_year'])[['join_year']].count() # Số lượng sốp␣
↪theo năm

axs[0,0].bar(count_shop.index, count_shop.join_year, width=0.5)


plt.ioff()
axs[0,0].set_title('Number of New Shops Over Years', fontsize=16)
axs[0,0].set_xlabel('Year', fontsize=14)
axs[0,0].set_ylabel('Number of Shops', fontsize=14)

[6]: Text(0, 0.5, 'Number of Shops')

3
[7]: # Yêu cầu 2
df_sub = o_c('response_rate','rating_good', df) # Truyền 2 thuộc tính và␣
↪DataFrame vào để nhận DataFrame mới được xử lý

colors = np.random.randint(10, 20, size=df_sub.shape[0]) # Thêm tí màu mè vào␣


↪các điểm dữ liệu

axs[0,1].scatter(df_sub['response_rate'], df_sub['rating_good'], c=colors)


axs[0,1].set_title('Response rate with Rating good', fontsize=16)
axs[0,1].set_xlabel('Response rate', fontsize=14)
axs[0,1].set_ylabel('Rating good', fontsize=14)
a1 = linear_reg('response_rate', 'rating_good', df_sub) # Tính hệ số của đường␣
↪hồi quy

axs[0,1].plot(df_sub.response_rate, a1[0]*df_sub.response_rate+a1[1], color='r')

[7]: [<matplotlib.lines.Line2D at 0x1ef3cb36d60>]

[8]: # Yêu cầu 3


# Cần đổi định dạng thời gian về giây (seconds)

df_sub = df.loc[:] # Copy theo phương thức .loc để tránh lỗi


df_sub['response_time'] = [e.strip() for e in df.response_time] # Xóa các␣
↪khoảng trắng giá trị response_time

df_sub['response_time'] = pd.to_datetime(df_sub['response_time'], format='%H:%M:


↪%S').dt.time # Đổi sang kiểu datetime với phương thức thuộc Pandas

df_sub['response_time'] = [(int(e.strftime('%H'))*int(e.
↪strftime('%M'))*60+int(e.strftime('%S'))) for e in df_sub.response_time]

# Phương thức strftime của Python giúp trích xuất thông tin giờ, phút, giây từ␣
↪text

4
# Ép về int do phương thức strftime trả về kiểu str. Tính ra giây: 1 giờ = 60␣
↪phút, 1 phút = 60 giây -> hour*minute*60 + second

df_sub2 = o_c('response_time','rating_bad',df_sub)

colors = np.random.randint(10, 20, size=df_sub2.shape[0]) # Thêm tí màu mè cho␣


↪sinh động

axs[0,2].scatter(df_sub2['response_time'], df_sub2['rating_bad'], c=colors)


axs[0,2].set_title('Response time with Rating bad', fontsize=16)
axs[0,2].set_xlabel('Response time (seconds)', fontsize=14)
axs[0,2].set_ylabel('Rating bad', fontsize=14)
a1 = linear_reg('response_time', 'rating_bad', df_sub2) # Tính hệ số của đường␣
↪hồi quy

axs[0,2].plot(df_sub2.response_time, a1[0]*df_sub2.response_time+a1[1],␣
↪color='r')

[8]: [<matplotlib.lines.Line2D at 0x1ef3d5c8340>]

[9]: # Yêu cầu 4


from datetime import datetime # Thư viện giúp xử lý các vấn đề về thời gian

year = df_sub['join_year']
month = df_sub['join_month']
day = df_sub['join_day']
combin = ['{} {} {}'.format(year[i], month[i], day[i]) for i in␣
↪range(len(df_sub.index))] # Hợp các giá trị thời gian lại để phục vụ mục␣

↪đích xử lý

df['join_time'] = combin # Tạo một cột mới trong bộ dữ liệu để thêm các giá trị␣
↪thời gian vừa hợp vào

df_sub = df.loc[:] # Tránh lỗi copy DataFrame


df_sub['join_time'] = [datetime.strptime(e, '%Y %B %d') for e in␣
↪df_sub['join_time']]

# Xử lý thời gian dạng text sang datetime object, các ký tự anh em xem thêm tại␣
↪link dưới để hiểu

# Tham khảo: https://www.programiz.com/python-programming/datetime/


↪strptime#google_vignette

# https://www.geeksforgeeks.org/python-datetime-strptime-function/
# https://stackoverflow.com/questions/25146121/
↪extracting-just-month-and-year-separately-from-pandas-datetime-column

# df_sub['join_time'] = pd.to_datetime(df_sub.join_time) # Phải ép về kiểu của␣


↪Pandas để extract ra year, month, day. p/s: khó hiểu thật sự

count_join = df_sub.groupby(df_sub.join_time.dt.to_period('M'))[['join_time']].
↪count() # Nhóm theo tháng, hoặc anh em thích nhóm theo ngày thì chuyển M ->␣

↪D, hoặc theo năm thì Y

5
axs[1,0].plot(np.asarray([str(e) for e in count_join.index]),count_join.
↪join_time, linewidth=3, marker='*', markersize=10, markerfacecolor='red')

axs[1,0].set_title('New Vendors by Months', fontsize=16)


axs[1,0].set_xlabel('Months', fontsize=14)
axs[1,0].set_ylabel('Number of Vendors', fontsize=14)
axs[1,0].xaxis.set_major_locator(tk.MaxNLocator(8)) # Đoạn này dùng để xoay␣
↪ngày tháng trục x cho dễ nhìn

# Tham khao: https://saturncloud.io/blog/


↪optimizing-tick-label-text-and-frequency-in-matplotlib-plots/

axs[1,0].set_xticklabels(axs[1,0].get_xticklabels(), rotation=45) # the same

C:\Users\Dell\AppData\Local\Temp\ipykernel_11072\1038879872.py:26: UserWarning:
FixedFormatter should only be used together with FixedLocator
axs[1,0].set_xticklabels(axs[1,0].get_xticklabels(), rotation=45) # the same

[9]: [Text(-8.0, 0, '0.0'),


Text(0.0, 0, '0.2'),
Text(8.0, 0, '0.4'),
Text(16.0, 0, '0.6'),
Text(24.0, 0, '0.8'),
Text(32.0, 0, '1.0'),
Text(40.0, 0, ''),
Text(48.0, 0, ''),
Text(56.0, 0, ''),
Text(64.0, 0, '')]

[10]: # Yêu cầu 5


# Cần xử lý một chút đoạn loại bỏ ngoại lai
df_sub = df[['rating_normal']].dropna()
z = np.abs(stats.zscore(df_sub.rating_normal))
df_sub_2 = df_sub[z<0.3]
axs[1,1].hist(df_sub_2.rating_normal, bins=5, density=True)
axs[1,1].set_title('Histogram: Frequency of Normal Rating', fontsize=16)
axs[1,1].set_xlabel('Normal Rating Score', fontsize=14)
fig.delaxes(axs[1][2]) # Xóa Axes thứ 6 do có 5 yêu cầu thôi :)
plt.tight_layout()
plt.show()

<Figure size 640x480 with 0 Axes>

[ ]:

You might also like