【发布时间】:2018-04-10 11:45:58
【问题描述】:
我希望用户能够上传 csv 文件,然后在 Bokeh 中对其进行处理和可视化。输入文件有三列(a、b 和 c),我想读取其中的两列进行显示。
我从https://github.com/bokeh/bokeh/issues/6096 复制了一些东西来获得一个Javascript 输入按钮。
现在我的输入文件正在控制台中显示,但我不知道如何将它放入 DataTable 小部件中。我需要写一个更新函数还是什么?感谢您的帮助!
import pandas as pd
from bokeh.layouts import row
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import Button, DataTable, TableColumn
from bokeh.io import curdoc
import io
import base64
file_source = ColumnDataSource(data=dict(a=[],b=[],c=[]))
def file_callback(attr,old,new):
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.StringIO(bytes.decode(file_contents))
df = pd.read_csv(file_io)
print('file contents:', df)
return df
file_source.on_change('data', file_callback)
columns = [
TableColumn(field="a", title="a"),
TableColumn(field="b", title="b")
]
table = DataTable(source=file_source.data,columns=columns, width=400)
button = Button(label="Upload", button_type="success")
button.callback = CustomJS(args=dict(file_source=file_source,table=table), 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();
""")
curdoc().add_root(row(button,table))
【问题讨论】:
标签: javascript python datatable bokeh