/
analytics.py
233 lines (221 loc) · 11.4 KB
/
analytics.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
221
222
223
224
225
226
227
228
229
230
231
232
233
import pdb
import streamlit as st
import streamlit.components.v1 as components
import pandas as pd
import numpy as np
import seaborn as sns
import Statistics as stats
import base64
from pandas_profiling import ProfileReport
import os
from streamlit_pandas_profiling import st_profile_report
def run(st,data):
expander = st.beta_expander("Menu",expanded=True)
with expander:
ana_choice = st.radio("Analysis",["Data","Visualization","Statistics","Data Profiling"])
filters = st.checkbox('Add Filters')
if filters:
st.info("Select column and values from below")
filtered_cols = st.multiselect("Select columns to filter",data.columns.tolist())
filtered_sets = []
if len(filtered_cols)>0:
iterations = len(filtered_cols) // 3
difference = len(filtered_cols) % 3
jack = 0
while jack < iterations:
cols_filtered = []
try:
cols_filtered = cols_filtered + st.beta_columns(3)
except:
pass
counter = 0
for i in range(jack*3, 3*jack+3):
filtered_sets.append(cols_filtered[counter].multiselect(filtered_cols[i], data[filtered_cols[i]].unique().tolist()))
counter+=1
jack+=1
if difference == 0:
pass
else:
cols_filtered = []
cols_filtered = cols_filtered + st.beta_columns(difference)
counter = 0
for i in range(iterations*3, iterations*3+difference):
filtered_sets.append(cols_filtered[counter].multiselect(filtered_cols[i], data[filtered_cols[i]].unique().tolist()))
counter += 1
#Now filtering the data
tracker = 0
for filter_value in filtered_sets:
if len(filter_value)>0:
data = data[data[filtered_cols[tracker]].isin(filter_value)]
tracker+=1
if ana_choice == 'Data':
data_options = st.selectbox("",["View Records","Data Correlation","Pivot"])
if data_options == "View Records":
c1,c2 = st.beta_columns(2)
top_bottom_options = c1.radio("Records",["Top","Bottom"])
num_rec = c2.number_input("No. of Records:", min_value=0, max_value=100, step=1, value=10)
if top_bottom_options == 'Top':
st.dataframe(data.head(num_rec))
else:
st.dataframe(data.tail(num_rec))
elif data_options == "Data Correlation":
select_columns = st.multiselect("Select Columns",data.columns.tolist())
corr_view = st.radio("Correlation View",["Table","Chart"])
if corr_view == 'Table':
if len(select_columns)==0:
st.dataframe(data.corr())
else:
st.dataframe(data[select_columns].corr())
else:
if len(select_columns) == 0:
st.write(sns.heatmap(data.corr(), annot=True))
st.pyplot()
else:
st.write(sns.heatmap(data[select_columns].corr(), annot=True))
st.pyplot()
elif data_options == 'Pivot':
dimensions = st.multiselect("Select X axis columns",data.columns.tolist())
measures = st.multiselect("Select Y axis columns", data.columns.tolist())
numeric_cols = st.multiselect("Aggregation columns", data.columns.tolist())
aggregation_operations = st.selectbox("Aggregation Operation",['sum','average','median','count'])
button = st.button("Execute!!!")
if button:
if len(numeric_cols) > 0 :
if aggregation_operations == 'sum':
operation = np.sum
elif aggregation_operations == 'average':
operation = np.mean
elif aggregation_operations == 'median':
operation = np.median
elif aggregation_operations == 'count':
operation = np.count_nonzero
pivot_table = pd.pivot_table(data,values=numeric_cols,index=measures,columns=dimensions,aggfunc=operation)
st.dataframe(pivot_table)
elif ana_choice == "Visualization":
chart_options = st.selectbox('Charts',['Bar','Line','Heatmap','Distplot','Customized'])
if chart_options == 'Bar':
x_col = st.selectbox('X',data.columns.tolist())
y_col = st.selectbox('Y', data.columns.tolist())
hue_color = st.checkbox("Add color column")
direction = st.radio('chart direction',['vertical','horizontal'])
if hue_color:
hue_col = st.selectbox('hue', data.columns.tolist())
button = st.button("Execute!!!")
if button:
if direction == 'vertical':
chart_direction = 'v'
else:
chart_direction = 'h'
if hue_color:
if hue_col:
st.write(sns.barplot(x=x_col, y=y_col, hue=hue_col, data=data,orient=chart_direction))
st.pyplot()
else:
st.write(sns.barplot(x=x_col, y=y_col, data=data,orient=chart_direction))
st.pyplot()
else:
st.write(sns.barplot(x=x_col, y=y_col, data=data, orient=chart_direction))
st.pyplot()
elif chart_options == 'Line':
x_col = st.selectbox('X', data.columns.tolist())
y_col = st.selectbox('Y', data.columns.tolist())
hue_color = st.checkbox("Add color column")
if hue_color:
hue_col = st.selectbox('hue', data.columns.tolist())
button = st.button("Execute!!!")
if button:
if hue_color:
if hue_col:
st.write(sns.lineplot(x=x_col, y=y_col, hue=hue_col, data=data))
st.pyplot()
else:
st.write(sns.lineplot(x=x_col, y=y_col, data=data))
st.pyplot()
else:
st.write(sns.lineplot(x=x_col, y=y_col, data=data))
st.pyplot()
elif chart_options == 'Heatmap':
select_columns = st.multiselect("Select Columns", data.columns.tolist())
button = st.button("Execute!!!")
if button:
if len(select_columns) == 0:
st.write(sns.heatmap(data, annot=True))
st.pyplot()
else:
st.write(sns.heatmap(data[select_columns], annot=True))
st.pyplot()
elif chart_options == 'Distplot':
x_col = st.selectbox('X', data.columns.tolist())
col = st.selectbox('column', data.columns.tolist())
row = st.selectbox('row', data.columns.tolist())
button = st.button("Execute!!!")
if button:
st.write(sns.displot(
data, x=x_col, col=col, row=row,
binwidth=3, height=3, facet_kws=dict(margin_titles=True),
))
st.pyplot()
elif chart_options == 'Customized':
code_area = st.text_area("""Enter your chart script, Return result to value.
e.g.
a = 3
b = 4
value = a + b!!!, Don't enter data parameter !!!""")
button = st.button("Execute!!!")
if button:
loc = {}
exec(code_area, {'data':data}, loc)
return_workaround = loc['value']
st.write(return_workaround)
st.pyplot()
elif ana_choice == 'Statistics':
test_selection = st.selectbox('Category',
['Value Count', 'Normality Test', 'Correlation Test', 'Stationary Test',
'Parametric Test',
'Non Parametric Test'])
statistics = stats.Statistics(data)
if test_selection == 'Value Count':
select_columns = st.selectbox("Select Columns",data.columns.tolist())
mode = st.radio('Value Counts',['Table','Chart'])
if mode == 'Table':
value_counts = statistics.__get__stats__(select_columns)
st.dataframe(value_counts)
else:
value_counts = statistics.__get__stats__(select_columns)
st.write(value_counts[:20].plot(kind='barh'))
st.pyplot()
elif test_selection == 'Normality Test':
st.write("""
Tests whether a data sample has a Gaussian distribution. \n
H0: the sample has a Gaussian distribution. \n
H1: the sample does not have a Gaussian distribution""")
select_test = st.selectbox('Tests', ['ShapiroWilk', 'DAgostino', 'AndersonDarling'])
col = st.selectbox('Select Column', data.columns.tolist())
text_option = st.checkbox('Text')
chart_option = st.checkbox('Chart')
if text_option:
t,p = statistics.normality_tests(data[col], test_type=select_test)
st.write('#### ' + t + " (" + str(p) + ")")
if chart_option:
st.write(sns.kdeplot(x=col,data=data))
st.pyplot()
elif ana_choice == 'Data Profiling':
st.markdown("""
##### The Data Profiling is done automatically using Pandas Profiling tool.\n \n \n \n
""")
limited_records = st.checkbox("Execute on Limited Records!!!")
select_columns = st.multiselect("Select Columns", data.columns.tolist())
if len(select_columns) == 0:
cols = data.columns.tolist()
else:
cols = select_columns
if limited_records:
num_rec = st.number_input("No. of Records:", min_value=0, max_value=1000000, step=1, value=100)
else:
num_rec = len(data)
execute_profiling = st.button('Execute!!!')
if execute_profiling:
st.title(f"Pandas Profiling on {num_rec} records")
report = ProfileReport(data[cols].loc[:num_rec,:], explorative=True)
st.write(data)
st_profile_report(report)