-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrangling.py
220 lines (160 loc) · 5.75 KB
/
wrangling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import pandas as pd
import seaborn as sns
import numpy as np
import sqlite3
import matplotlib.pyplot as plt
def mapping_translation():
"""_summary_
Returns:
_type_: _description_
"""
querry = """
SELECT * FROM product_category_name_translation
"""
product_category_name_translation = pd.read_sql(
querry, sqlite3.connect("dataset/olist.db")
)
mapping = {}
for i in range(len(product_category_name_translation)):
original = product_category_name_translation.iloc[i][1]
english = product_category_name_translation.iloc[i][2]
mapping[original] = english
return mapping
def kde_multiple_plot(data: str, n_row: int, fig_size: tuple = tuple()):
"""_summary_
Args:
data (str): _description_
n_row (int): _description_
fig_size (tuple, optional): _description_. Defaults to tuple().
"""
# create subplots with 11x3 grids and size 12x30
fig, ax = plt.subplots(n_row, 3, figsize=fig_size)
try:
# counter to select colnames
cnt = 0
# loop through the grids
for i in range(n_row):
if cnt >= n_row * 3:
break
for j in range(3):
if cnt >= n_row * 3:
break
# we use boxplot from pyplot
x = data.columns[cnt]
sns.kdeplot(data=data, x=x, ax=ax[i, j])
# draw vertical line to describe the mean value
ax[i, j].axvline(
x=data[x].mean(), color="b", linestyle="--", label="mean"
)
# draw vertical line to describe the median value
ax[i, j].axvline(
x=data[x].median(),
color="g",
linestyle="-.",
label="median",
)
# increment counter
cnt = cnt + 1
# make sure layout is not overlapping
fig.tight_layout()
# show the legend
ax[0, 2].legend(loc="upper right")
# show the graphs
plt.show()
except IndexError:
# make sure layout is not overlapping
fig.tight_layout()
# show the legend
ax[0, 2].legend(loc="upper right")
# show the graphs
plt.show()
def boxplot_multiple_plot(data: str, n_row: int, fig_size=tuple()):
"""_summary_
Args:
data (str): _description_
n_row (int): _description_
fig_size (tuple, optional): _description_. Defaults to tuple().
"""
# create subplots with 11x3 grids and size 12x30
fig, ax = plt.subplots(n_row, 3, figsize=fig_size)
try:
# counter to select colnames
cnt = 0
# loop through the grids
for i in range(n_row):
if cnt >= n_row * 3:
break
for j in range(3):
if cnt >= n_row * 3:
break
# we use boxplot from pyplot
x = data.columns[cnt]
sns.boxplot(data=data, x=x, ax=ax[i, j])
# increment counter
cnt = cnt + 1
# make sure layout is not overlapping
fig.tight_layout()
# show the graphs
plt.show()
except IndexError:
# make sure layout is not overlapping
fig.tight_layout()
# show the graphs
plt.show()
def subplots_dayname_timeday(
data: pd.DataFrame,
column_name_1: str,
column_name_2: str,
title: str,
parse_by: str = "order_id",
):
"""_summary_
Args:
data (pd.DataFrame): _description_
column_name_1 (str): _description_
column_name_2 (str): _description_
title (str): Judul Figure
parse_by (str, optional): _description_. Defaults to 'order_id'.
"""
fig, ax = plt.subplots(1, 2, figsize=(16, 8))
sns.countplot(data=data, x=column_name_1, ax=ax[0], palette="YlGnBu")
# Create Absolute Value for labels
abs_values = data.groupby(column_name_1)[parse_by].count().to_list()
# Create Relative Value for labels
rel_values = [val / np.sum(abs_values) for val in abs_values]
# Labels Formatting
lbls = [f"{p[0]}\n({p[1]:.2%})" for p in zip(abs_values, rel_values)]
# Assign label into plot
ax[0].bar_label(container=ax[0].containers[0], labels=lbls, padding=5)
# Create weekday label in order
weekday_label = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
# Assign weekday label using xticklabels
ax[0].set_xticklabels(weekday_label)
sns.countplot(data=data, x=column_name_2, ax=ax[1], palette="coolwarm_r")
# Create Absolute Value for labels
abs_values = data.groupby(column_name_2)[parse_by].count().to_list()
# Create Relative Value for labels
rel_values = [val / np.sum(abs_values) for val in abs_values]
# Labels Formatting
lbls = [f"{p[0]}\n({p[1]:.2%})" for p in zip(abs_values, rel_values)]
# Assign label into plot
ax[1].bar_label(container=ax[1].containers[0], labels=lbls, padding=5)
fig.suptitle(f"{title}\n")
fig.tight_layout()
plt.show()
def check_missing_value(data: pd.DataFrame):
"""Function to check missing value in dataframe
Args:
data (pd.DataFrame): dataframe to be checked
Returns:
DataFrame: dataframe that contains missing values in percentage
"""
# sum all missing value in dataset and
# keep only columns with missing value > 0
missing = data.isnull().sum()[data.isnull().sum() > 0]
# construct a dataframe consists of NaN count and
# NaN percentage from the dataset
missing_df = pd.DataFrame(
{"NaN_count": missing, "NaN_percentage": missing / len(data)}
).sort_values(by="NaN_percentage", ascending=False)
return missing_df