-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
291 lines (226 loc) · 8.36 KB
/
app.py
File metadata and controls
291 lines (226 loc) · 8.36 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""This script creates a local WebApp for EDA and interactive data manipulation"""
import base64
import datetime
import io
import pandas as pd
import streamlit as st
from plotly import graph_objs as go
DATA_PATH = "data/weatherlink_data_on_site_updated.parquet"
st.set_page_config(page_title="Data Visualization",
page_icon=None,
layout="centered",
initial_sidebar_state="auto",
menu_items=None)
st.write("Hello :wave:")
st.write("In this simple WebApp, I will try to do how to EDA and manipulate data interactively :dart:")
st.write("Here is my [Github account](https://github.com/egenc) to give you a glimpse what kind of projects I am working on.")
with st.sidebar:
st.markdown("[#1. Checking counts of :blue[NaN values]:](Section 1)", unsafe_allow_html=True)
@st.cache_data
def load_data(path):
"""loads input data"""
return pd.read_parquet(path)
df = load_data(DATA_PATH)
st.title(':seedling: Data Visualization with Streamlit :seedling:')
st.write("Data looks like this: (click top right icon to expand)")
st.write(df.head())
st.write("---")
st.subheader(':exclamation: _Some Insights About Data_ :exclamation:')
col1, col2 = st.columns(2)
with col1:
op_type = st.radio(
"What would you like to know about data :point_down:",
options=["columns", "description", "info", "shape", "none"],
)
with col2:
df_ops = {"columns": df.columns,
"description": df.describe(),
"shape": f"(num_rows, num_columns): **{df.shape}**" ,
"none": "Please select a box on the left to get insights about data"}
if op_type == "info":
buffer = io.StringIO()
df.info(buf=buffer)
s = buffer.getvalue()
st.text(s)
else:
st.markdown("**Slide left-right to explore:**")
st.write(df_ops[op_type])
st.write("---")
st.subheader("1. Checking counts of :blue[NaN values]:")
st.write(df.isnull().sum())
st.write("---")
st.write("**For a start, let's drop columns with too many :blue[NaN values]:**")
st.write("Do you agree to drop columns **['2nd Temp - °C', 'High Wind Direction', 'Wind Direction']** with too many NaN values:")
agree = st.checkbox('I agree')
if agree:
df.drop(['2nd Temp - °C', 'High Wind Direction', 'Wind Direction'], axis=1, inplace=True)
st.write(df.head())
st.write("---")
st.write("Let's check counts of :blue[NaN values] again:")
st.write(df.isnull().sum())
col1, col2 = st.columns(2)
with col1:
nan_op = st.radio(
"How would you like to handle NaN values :point_down:",
options=["drop rows with NaN", "Replace NaNs with a numerical value"],
)
with col2:
if nan_op == "drop rows with NaN":
df.dropna(inplace=True)
else:
number = st.number_input('Insert a number to replace NaNs:', min_value=0)
df.fillna(number, inplace=True)
st.write("**Let's check counts of :blue[NaN values] one last time:**")
st.dataframe(df.isnull().sum())
st.write("Average Windspeed: :tornado:", df["Wind Speed - km/h"].mean())
st.write("Average Temperature: :mostly_sunny:", df["Temp - °C"].mean())
st.write("---")
st.subheader("2. Checking :blue[Repeating Values]")
col1, col2 = st.columns(2)
with col1:
N_repetative = int(st.number_input('Amount of repetative values: (i. e. 5)',
max_value=len(df), min_value=4))
col = st.radio(
"Please select a column to check repetative values :point_down:",
options=df.columns,
)
@st.cache_data
def get_value_counts(d_frame):
"""gets value counts of a specific column"""
counts = d_frame.value_counts()
return counts[counts > N_repetative].index.tolist()
with col2:
matches = get_value_counts(df[col])
st.write(f"**__Values in :red[{col}] that occur more than :red[{N_repetative}] times:__** {matches}")
st.write("---")
st.subheader(":hourglass_flowing_sand: 3. Checking Timestamps :hourglass_flowing_sand:")
st.write("- Duplicate TimeStamps (if exists):")
duplicates_mask = df.duplicated(['DateTime'], keep=False)
st.write(df[duplicates_mask])
st.write("- Select Dates: :warning:(Please pick time carefully as dataframe will change accordingly and so are results):warning:")
col1, col2 = st.columns(2)
with col1:
d_min = st.date_input(
":red[Start Date]",
datetime.date(2020, 11, 3),
key="start_date")
t_min = st.time_input(':red[Start time]', datetime.time(16, 00),
key="start_time")
dt_min = datetime.datetime.combine(d_min, t_min)
with col2:
d_max = st.date_input(
":blue[End Date]",
datetime.datetime.now(),
key="end_date")
t_max = st.time_input(':blue[End time]',
datetime.time(00, 00),
key="end_time")
dt_max = datetime.datetime.combine(d_max, t_max)
mask = (df['DateTime'] >= dt_min) & (df['DateTime'] <= dt_max)
df = df.loc[mask]
st.write("---")
ticked = st.checkbox('I want to see statistics of data between selected dates.')
if ticked:
col1, col2 = st.columns(2)
with col1:
op_type = st.radio(
"Explore data👉",
options=["columns", "description", "info", "shape", "none"],
)
with col2:
df_ops = {"columns": df.columns,
"description": df.describe(),
"shape": f"(num_rows, num_columns): **{df.shape}**" ,
"none": "Please select a box on the left to get insights about data"}
if op_type == "info":
buffer = io.StringIO()
df.info(buf=buffer)
s = buffer.getvalue()
st.text(s)
else:
st.markdown("**Slide left-right to explore:**")
st.write(df_ops[op_type])
st.write("---")
st.write("- Check outliers:")
col1, col2 = st.columns(2)
with col1:
N_repetative = int(st.number_input('Amount of std from mean (i. e. 5)',
max_value=30,
min_value=1))
col = st.radio(
"Please select a column to check std-mean relation👉",
options=df.columns,
)
with col2:
try:
column = df[col]
mean = column.mean()
std = column.std()
outliers = column[(column > mean + N_repetative * std) | (column < mean - N_repetative * std)]
st.write("Outlier values:")
st.write(outliers)
except TypeError:
pass
# Add a download button to download the dataframe as a CSV file
csv = df.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode()
st.download_button(
label=":inbox_tray: Download latest CSV with changes :inbox_tray:",
data=csv,
file_name='saved_csv.csv',
mime='text/csv'
)
st.write("---")
# Plot raw data
def plot_raw_data(cols_list):
"""Plots columns based on Time"""
fig = go.Figure()
for s_col in cols_list:
fig.add_trace(go.Scatter(x=df['DateTime'], y=df[s_col], name=f"Time over {s_col}"))
fig.layout.update(title_text=f'Time Series data with column {cols_list}',
xaxis_rangeslider_visible=True)
return fig
st.write("---")
options = st.multiselect(
'please select the columns to plot',
df.columns,
['Temp - °C', 'Wind Speed - km/h']
)
st.write("Please expand the small chart below to zoom in & out")
fig = plot_raw_data(options)
st.plotly_chart(fig)
# Create an in-memory buffer
buffer = io.BytesIO()
# Save the figure as a pdf to the buffer
fig.write_image(file=buffer, format="pdf")
# Download the pdf from the buffer
st.download_button(
label=":inbox_tray: Download graph as PDF :inbox_tray:",
data=buffer,
file_name="results/figure.pdf",
mime="application/pdf",
)
st.write("---")
# Compute the correlation matrix
corr_matrix = df.corr(numeric_only=True)
# Create a heatmap plot of the correlation matrix using plotly
fig = go.Figure(data=go.Heatmap(
z=corr_matrix.values,
x=corr_matrix.columns,
y=corr_matrix.index,
colorscale='RdBu',
reversescale=True,
zmin=-1,
zmax=1))
# Customize the plot layout
fig.update_layout(
title="Correlation Matrix",
xaxis_title="Features",
yaxis_title="Features",
width=1000, # Set the width of the figure
height=1000, # Set the height of the figure
margin=dict(l=40, r=40, b=40, t=40),
paper_bgcolor="black",
)
# Display the plot
st.plotly_chart(fig)