【发布时间】:2018-01-19 01:47:04
【问题描述】:
我需要您对我几天以来面临的一些挑战提供意见。
我的目标是有一个上传按钮,我从中分享.xlsx 文件和两张纸。一旦我加载这些数据并将其读入pandas DataFrame,我执行一些pythonic计算/优化代码等并得到很少的结果(表格总结)。现在,根据唯一“级别”/“组”的数量,我将创建那么多选项卡,然后在每个选项卡中显示此汇总结果。在主页中也有一个一般(通用)图。
以下是我的努力(不是我的,而是社区的:)):
1。上传按钮代码:(来自here)
## Load library
###########################################################################
import pandas as pd
import numpy as np
from xlrd import XLRDError
import io
import base64
import os
from bokeh.layouts import row, column, widgetbox, layout
from bokeh.models import ColumnDataSource, CustomJS, LabelSet
from bokeh.models.widgets import Button, Div, TextInput, DataTable, TableColumn, Panel, Tabs
from bokeh.io import curdoc
from bokeh.plotting import figure
###########################################################################
## Upload Button Widget
file_source = ColumnDataSource({'file_contents':[], 'file_name':[]})
cds_test = ColumnDataSource({'v1':[], 'v2':[]})
def file_callback(attr,old,new):
global tabs, t
print('filename:', file_source.data['file_name'])
raw_contents = file_source.data['file_contents'][0]
prefix, b64_contents = raw_contents.split(",", 1)
file_contents = base64.b64decode(b64_contents)
file_io = io.BytesIO(file_contents)
# Here it errors out when trying '.xlsx' file but work for .csv Any Idea ????
#df1 = pd.read_excel(file_io, sheet = 'Sheet1')
#df2 = pd.read_excel(file_io, sheet = 'Sheet2')
# call some python functions for analysis
# returns few results
# for now lets assume main_dt has all the results of analysis
df1 = pd.read_excel(file_path, sheet_name = 'Sheet1')
df2 = pd.read_excel(file_path, sheet_name = 'Sheet2')
main_dt = pd.DataFrame({'v1':df1['v1'], 'v2': df2['v2']})
level_names = main_dt['v2'].unique().tolist()
sum_v1_level = []
for i in level_names:
csd_temp = ColumnDataSource(main_dt[main_dt['v2'] == i])
columns = [TableColumn(field=j, title="First") for j in main_dt.columns]
dt = DataTable(source = csd_temp, columns = columns, width=400, height=280)
temp = Panel(child = dt, title = i)
t.append(temp)
sum_v1_level.append(sum(csd_temp.data['v1']))
tabs = Tabs(tabs = t)
cds_plot = ColumnDataSource({'x':level_names, 'y':sum_v1_level})
p_o = figure(x_range = level_names, plot_height=250, title="Plot")
p_o.vbar(x='x', top = 'y', width=0.9, source = cds_plot)
p_o.xgrid.grid_line_color = None
p_o.y_range.start = 0
p_o.y_range.end = max(sum_v1_level)*1.2
labels_o = LabelSet(x='x', y = 'y', text='y', level='glyph',
x_offset=-13.5, y_offset=0, render_mode='canvas', source = cds_plot)
p_o.add_layout(labels_o)
curdoc().add_root(p_o)
curdoc().add_root(tabs)
print('successful upload')
file_source.on_change('data', file_callback)
button = Button(label="Upload Data", button_type="success")
# when butotn is clicked, below code in CustomJS will be called
button.callback = CustomJS(args=dict(file_source=file_source), code = """
function read_file(filename) {
var reader = new FileReader();
reader.onload = load_handler;
reader.onerror = error_handler;
// readAsDataURL represents the file's data as a base64 encoded string
reader.readAsDataURL(filename);
}
function load_handler(event) {
var b64string = event.target.result;
file_source.data = {'file_contents' : [b64string], 'file_name':[input.files[0].name]};
file_source.trigger("change");
}
function error_handler(evt) {
if(evt.target.error.name == "NotReadableError") {
alert("Can't read file!");
}
}
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function(){
if (window.FileReader) {
read_file(input.files[0]);
} else {
alert('FileReader is not supported in this browser');
}
}
input.click();
""")
Bdw:有什么方法可以抑制这个警告还是我做错了?(在将读取列插入 CDS 时)
BokehUserWarning:ColumnDataSource 的列必须具有相同的长度。当前长度:('v1', 19), ('v2', 0)
2。添加到布局中
curdoc().title = 'Test Joel'
curdoc().add_root(button)
这是原始数据: 注意:这里分享的所有数据都是虚拟的,真实案例有更多的表和更多的维度。
总结一下:
-
无法通过上传按钮读取
.xlsx文件 -
在按钮回调函数本身中执行所有步骤是否正确?
【问题讨论】:
标签: python pandas web-applications bokeh