I'm trying to follow this interactive widget tutorial:
Python-Data Projects — Data Analysis UI Reinforced by Ipywidgets,
but every time I get a No CSV loaded
error. This happens when I try to upload the csv and click on Preview
.
import pandas as pd
import sys
from io import StringIO
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
%matplotlib inline
tab = widgets.Tab()
out = widgets.Output(layout={'border': '1px solid black'})
up = widgets.FileUpload(accept="", multiple=False)
delim = widgets.RadioButtons(
options=[';', ',', ' '],
description='Separator: ',
disabled=False)
eraser = widgets.SelectMultiple(
options=['tab','"'],
value=['tab'],
#rows=10,
description='Eraser: ',
disabled=False)
rows = widgets.IntSlider(
value=0,
step=1,
description='# of lines:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='d')
button_upload = widgets.Button(
description='Upload',
disabled=False,
button_style='warning',
tooltip='Click to Upload',
icon='check')
button_preview = widgets.Button(
description='Preview',
disabled=False,
button_style='info',
tooltip='Click to Preview',
icon='search')
button_plot = widgets.Button(
description='Plot',
disabled=False,
button_style='danger',
tooltip='Click to Plot',
icon='pencil')
graph_type = widgets.Dropdown(
options=['Bar Chart', 'Line Chart'],
value='Bar Chart',
description='Chart Type:',
disabled=False)
x_axis = widgets.Dropdown(
options=[''],
value='',
description='X-Axis:',
disabled=False)
y_axis = widgets.Dropdown(
options=[''],
value='',
description='Y-Axis:',
disabled=False)
color_picker = widgets.ColorPicker(
concise=False,
description='Color Picker: ',
value='lightblue',
disabled=False)
toggle = widgets.ToggleButtons(
options=['Preview ', 'Info ', 'Stats '],
description='Options',
disabled=False,
button_style='warning',
icons=['search', 'info', 'tachometer'])
accordion = widgets.Accordion(children=[
up,
widgets.VBox([delim, eraser]),
rows])
accordion.set_title(0, 'File Selection')
accordion.set_title(1, 'Delimiter')
accordion.set_title(2, 'Skip Rows')
accordion_box = widgets.VBox([
accordion,
widgets.HBox([button_preview, button_upload]),
out
])
children = [
accordion_box,
widgets.VBox([toggle, out]),
widgets.VBox([
widgets.HBox([graph_type, color_picker]),
widgets.HBox([x_axis, y_axis]),
button_plot,
out
])]
tab.children = children
tab.set_title(0, "Upload")
tab.set_title(1, "Describer")
tab.set_title(2, "Plotter")
display(tab)
def content_parser():
if up.value == {}:
with out:
print('No CSV loaded')
else:
typ, content = "", ""
up_value = up.value
for i in up_value.keys():
typ = up_value[i]["metadata"]["type"]
if typ == "text/csv":
content = up_value[i]["content"]
content_str = str(content, 'utf-8')
if eraser.value != {}:
for val in eraser.value:
if val == "tab":
content_str = content_str.replace("\t","")
else:
content_str = content_str.replace(val,"")
if content_str != "":
str_io = StringIO(content_str)
return str_io
def df_converter():
content = content_parser()
if content is not None:
df = pd.read_csv(content, sep=delim.value, index_col=False, skiprows=rows.value)
return df
else:
return None
def preview():
df = df_converter()
with out:
out.clear_output()
print('\n -----Now this is how your DF looks like:----- \n')
if df is not None:
print(df.head(10))
else:
print('Configuration is wrong/missing...')
def upload():
df = df_converter()
with out:
out.clear_output()
print('\n --------Your uploaded DF looks like:-------- \n')
if df is not None:
print(df)
x_axis.options = df.columns
y_axis.options = df.columns
else:
print('Configuration is wrong/missing...')
def desc():
info_level = toggle.value
if info_level != {}:
df = df_converter()
with out:
out.clear_output()
print('\n ------Your {} looks like:------ \n'.format(
info_level))
if df is not None:
if info_level == 'Info ':
print(df.info(verbose=True))
elif info_level == 'Stats ':
print(df.describe())
elif info_level == 'Preview ':
print(df.head(5))
else:
print('Configuration is wrong/missing...')
def plot():
graph = graph_type.value
if graph != {}:
df = df_converter()
with out:
out.clear_output()
print('\n ------Your {} looks like:------ \n'.format(
graph))
if (df is not None):
df = df.head(5)
height = df[y_axis.value]
bars = df[x_axis.value]
y_pos = np.arange(len(height))
plt.figure(figsize=(10,4))
if graph == 'Bar Chart':
plt.bar(
y_pos,
height,
color=color_picker.value)
plt.xticks(y_pos, bars)
elif graph == 'Line Chart':
plt.plot(
bars,
height,
color=color_picker.value,
marker='o',
linestyle='solid'
)
plt.xticks(bars)
plt.show()
def preview_clicked(b):
preview()
def upload_clicked(b):
upload()
def desc_clicked(b):
desc()
def plotter_clicked(b):
plot()
button_preview.on_click(preview_clicked)
button_upload.on_click(upload_clicked)
toggle.observe(desc_clicked, 'value')
button_plot.on_click(plotter_clicked)