# 우리가 볼 수 있듯이 orders.csv는 주문을 구매한 사용자, 구매한 날짜, 사전 주문일 등 특정 주문 ID에 대한 모든 정보를 가지고 있습니다.
# order_products_train과 order_products_prior에 있는 열이 동일합니다. 그렇다면 이 파일들의 차이점은 무엇입니까?
# 앞서 언급했듯이, 이 데이터셋에서는 4~100건의 고객 주문이 제공되며(이 내용은 나중에 확인) 재주문될 제품을 예측해야 합니다.
# 그래서 사용자의 마지막 주문을 꺼내 기차와 테스트 세트로 나누었습니다. 고객의 모든 이전 주문 정보는 order_products_prior 파일에 있습니다.
# 또한 orders.csv 파일에 지정된 행이 연결되는 세 개의 데이터 집합(사전, 교육 또는 테스트) 중 어떤 데이터 집합으로 구성되는지 알려 주는 열이 있습니다.
# 주문_products*csv 파일에는 재주문 상태와 함께 지정된 주문에서 구매한 제품에 대한 자세한 정보가 있습니다.
# 먼저 세 세트의 행 수를 계산해 보겠습니다.
In [19]:
cnt_srs = orders_df.eval_set.value_counts()
plt.figure(figsize=(12,8))
sns.barplot(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[1])
plt.xlabel('Eval set type', fontsize=12)
plt.ylabel('Number of Occurrences', fontsize=12)
plt.title('Count of rows in each dataset', fontsize = 15)
plt.xticks(rotation=0)
plt.show()
C:\Users\user\anaconda3\envs\datascience\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
C:\Users\user\anaconda3\envs\datascience\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
Out[38]:
<AxesSubplot:>
In [ ]:
# 따라서 데이터 페이지에 주어진 4개 미만의 주문은 없으며 최대 상한은 100입니다.
# 이제 요일에 따라 주문 습관이 어떻게 변하는지 알아보겠습니다.
In [39]:
plt.figure(figsize=(12,8))
sns.countplot(x="order_dow", data = orders_df, color=color[0])
plt.xlabel('Day of Week', fontsize=12)
plt.ylabel('Count', fontsize = 12)
plt.xticks(rotation=0)
plt.title("Frequency of order by week day", fontsize = 15)
plt.show()
In [ ]:
# 0과 1은 주문이 많은 토요일과 일요일이고 수요일에는 적은 것 같습니다.
# 이제 하루 중 시간에 대한 분배 상태를 알아보겠습니다.
In [40]:
plt.figure(figsize=(12,8))
sns.countplot(x="order_hour_of_day", data = orders_df, color=color[1])
plt.xlabel('Hour of day', fontsize=12)
plt.ylabel('Count', fontsize=12)
plt.xticks(rotation=0)
plt.title("Frequency of order by hour of day", fontsize=15)
plt.show()
In [ ]:
# 그래서 대부분의 주문은 낮에 이루어집니다. 이제 요일과 요일을 결합하여 분포를 살펴보겠습니다.
plt.figure(figsize=(12,8))
sns.heatmap(grouped_df)
plt.title("Frequency of Day of week VS. Hour of day")
plt.show()
In [ ]:
# 토요일 저녁과 일요일 아침이 황금시간대인 것 같습니다.
# 이제 주문 사이의 시간간격을 확인해 보겠습니다.
In [43]:
plt.figure(figsize=(12, 8))
sns.countplot(x="days_since_prior_order", data=orders_df, color=color[3])
plt.xlabel('Days since prior order', fontsize=12)
plt.ylabel('Count', fontsize=12)
plt.xticks(rotation=0)
plt.title("Frequency distribution by days since prior order", fontsize=15)
plt.show()
In [ ]:
# 고객이 일주일에 한 번(7일 피크 확인) 또는 한 달에 한 번(30일 피크) 주문하는 것으로 보입니다.
# 또한 14일, 21일, 28일(주간 간격)에 더 작은 봉우리를 볼 수 있었습니다.
# 우리의 목표는 재주문 파악이므로, prior set와 train set의 재주문 비율을 확인하도록 하겠습니다.
plt.figure(figsize=(12,8))
sns.barplot(cnt_srs.index, cnt_srs.values, alpha=0.8)
plt.xlabel('Number of Products in the given order', fontsize=12)
plt.ylabel('Number of Occurrences', fontsize=12)
plt.xticks(rotation=0)
plt.show()
C:\Users\user\anaconda3\envs\datascience\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
In [ ]:
# 최대값이 5인 오른쪽 꼬리 분포!
# 제품 세부 정보를 살펴보기 전에 나머지 세 파일도 살펴보겠습니다.
<ipython-input-62-a0cb5648fa4f>:1: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access
cnt_srs.colums = ['product_name', 'frequency_count']
Out[62]:
index
product_name
0
Banana
472565
1
Bag of Organic Bananas
379450
2
Organic Strawberries
264683
3
Organic Baby Spinach
241921
4
Organic Hass Avocado
213584
5
Organic Avocado
176815
6
Large Lemon
152657
7
Strawberries
142951
8
Limes
140627
9
Organic Whole Milk
137905
10
Organic Raspberries
137057
11
Organic Yellow Onion
113426
12
Organic Garlic
109778
13
Organic Zucchini
104823
14
Organic Blueberries
100060
15
Cucumber Kirby
97315
16
Organic Fuji Apple
89632
17
Organic Lemon
87746
18
Apple Honeycrisp Organic
85020
19
Organic Grape Tomatoes
84255
In [63]:
# 유기농 제품들이 대부분입니다. 또한 그것들 중 대다수는 과일입니다.
# 이제 중요한 aisles를 봅시다.
C:\Users\user\anaconda3\envs\datascience\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
In [66]:
# 맨 위의 두 통로는 신선한 과일과 신선한 야채입니다.
# 부서 분포:
# 이제 부서(코너?카테고리?) 별 분포를 확인하겠습니다.
C:\Users\user\anaconda3\envs\datascience\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
In [75]:
# Personal Care는 재주문 비율이 낮고 Dairy Eggs(유제품 계란)은 재주문 비율이 높다.
# Aisle - 재주문 비율:
grouped_df
Out[75]:
department
reordered
0
alcohol
0.569924
1
babies
0.578971
2
bakery
0.628141
3
beverages
0.653460
4
breakfast
0.560922
5
bulk
0.577040
6
canned goods
0.457405
7
dairy eggs
0.669969
8
deli
0.607719
9
dry goods pasta
0.461076
10
frozen
0.541885
11
household
0.402178
12
international
0.369229
13
meat seafood
0.567674
14
missing
0.395849
15
other
0.407980
16
pantry
0.346721
17
personal care
0.321129
18
pets
0.601285
19
produce
0.649913
20
snacks
0.574180
In [76]:
grouped_df = order_products_prior_df.groupby(["department_id", "aisle"])["reordered"].aggregate("mean").reset_index()
fig, ax = plt.subplots(figsize=(12,20))
ax.scatter(grouped_df.reordered.values, grouped_df.department_id.values)
for i, txt in enumerate(grouped_df.aisle.values) :
ax.annotate(txt, (grouped_df.reordered.values[i],
grouped_df.department_id.values[i]),
rotation=45, ha='center', va='center', color='green')
plt.xlabel('Reorder Ratio')
plt.ylabel('Department_id')
plt.title("Reorder Ratio of Different Aisles", fontsize=15)
plt.show()
In [77]:
# 장바구니에 추가 - 재주문 비율:
# 이제 카트에 제품을 추가하는 순서가 재주문 비율에 어떤 영향을 미치는지 살펴보겠습니다.
plt.figure(figsize=(12, 8))
sns.pointplot(grouped_df['add_to_cart_order_mod'].values, grouped_df['reordered'].values, alpha=0.8, color=color[2])
plt.xlabel('Add to cart order', fontsize=12)
plt.ylabel('Reorder Ratio', fontsize=12)
plt.title("Add to cart order - Reorder Ratio", fontsize=15)
plt.xticks(rotation='vertical')
plt.show()
C:\Users\user\anaconda3\envs\datascience\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
In [80]:
# 처음에 카트에 추가된 제품들은 나중에 추가된 제품들에 비해 재주문될 가능성이 더 높아 보입니다.
# 우리가 자주 구매하던 모든 제품을 먼저 주문하고 새로운 제품을 찾는 경향이 있기 때문에 저도 이 말은 이해가 됩니다.
In [81]:
# 시간 기반 변수별로 비율 재정렬:
order_products_train_df = pd.merge(order_products_train_df, orders_df, on='order_id', how='left')
grouped_df = order_products_train_df.groupby(["order_dow"])["reordered"].aggregate("mean").reset_index()
plt.figure(figsize=(12,8))
sns.barplot(grouped_df['order_dow'].values, grouped_df['reordered'].values, alpha=0.8, color=color[3])
plt.ylabel('Reorder ratio', fontsize=12)
plt.xlabel('Day of week', fontsize=12)
plt.title("Reorder ratio across day of week", fontsize=15)
plt.xticks(rotation='vertical')
plt.ylim(0.5, 0.7)
plt.show()
C:\Users\user\anaconda3\envs\datascience\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
In [82]:
grouped_df = order_products_train_df.groupby(["order_hour_of_day"])["reordered"].aggregate("mean").reset_index()
plt.figure(figsize=(12, 8))
sns.barplot(grouped_df['order_hour_of_day'].values, grouped_df['reordered'].values, alpha=0.8, color=color[4])
plt.xlabel('Hour of day', fontsize=12)
plt.ylabel('Reorder Ratio', fontsize=12)
plt.title("Reorder Ratio Across Hour of Day", fontsize=15)
plt.xticks(rotation='vertical')
plt.ylim(0.5, 0.7)
plt.show()
C:\Users\user\anaconda3\envs\datascience\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
In [83]:
grouped_df = order_products_train_df.groupby(["order_dow", "order_hour_of_day"])["reordered"].aggregate("mean").reset_index()
grouped_df = grouped_df.pivot('order_dow', 'order_hour_of_day', 'reordered')
plt.figure(figsize=(12, 6))
sns.heatmap(grouped_df)
plt.title("Reorder Ratio of Day of Week VS. Hour of Day")
plt.show()