Bokeh DataTable - 在选择回调时返回行和列 [英] Bokeh DataTable - Return row and column on selection callback

查看:30
本文介绍了Bokeh DataTable - 在选择回调时返回行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 on_change 回调,我可以在散景中获取数据表中选择的数字行索引.是否有可能:a) 获取列索引b) 获取索引的值(列和行标题)

示例代码:

from bokeh.io import curdoc从 bokeh.layouts 导入行、列将熊猫导入为 pd从 bokeh.models 导入 ColumnDataSource、ColorBar、DataTable、DateFormatter、TableColumn、HoverTool、Spacer、DatetimeTickFormatter'''熊猫'''df = pd.DataFrame(data = {'苹果': [5,10], '香蕉': [16,15], '橙子': [6,4]})df.rename(index={0:'A',1:'B'}, inplace=True)'''散景'''sourceTableSummary = ColumnDataSource(df)Columns = [TableColumn(field=colIndex, title=colIndex) for colIndex in df.columns]data_table = DataTable(columns=Columns, source=sourceTableSummary, index_position = 0, width = 1900, height = 200, fit_columns=False)'''函数'''def return_value(attr, old, new):selectionRowIndex=sourceTableSummary.selected.indices[0]打印(选定的行索引",str(selectionRowIndex))selectionValue=sourceTableSummary.data['Apples'][selectionRowIndex]print("选定的苹果值", str(selectionValue))#选择列索引?# selectionRowHeader?# selectionColumnHeader?sourceTableSummary.on_change('selected', return_value)curdoc().add_root(column(children=[data_table]))

这给出了可以返回行和选择中的值的以下内容.如果我总是想要返回单个列,这是理想的.然而,选择 UI(虚线)似乎表明特定列是已知的,而不仅仅是行.如果无法获得所选列,是否可以同时使用行索引和单元格值进行查找?

Using an on_change callback, I can get the numerical row index of a selection within a DataTable, in Bokeh. Is it possible to: a) Get the column index b) Get the values of the indexes (column and row headers)

Example code:

from bokeh.io import curdoc
from bokeh.layouts import row, column
import pandas as pd
from bokeh.models import ColumnDataSource, ColorBar, DataTable, DateFormatter, TableColumn, HoverTool, Spacer, DatetimeTickFormatter

'''
Pandas
'''

df = pd.DataFrame(data = {'Apples': [5,10], 'Bananas': [16,15], 'Oranges': [6,4]})
df.rename(index={0:'A',1:'B'}, inplace=True)

'''
BOKEH
'''

sourceTableSummary = ColumnDataSource(df)
Columns = [TableColumn(field=colIndex, title=colIndex) for colIndex in df.columns] 
data_table = DataTable(columns=Columns, source=sourceTableSummary, index_position = 0, width = 1900, height = 200, fit_columns=False) 

'''
Funcs
'''

def return_value(attr, old, new):
    selectionRowIndex=sourceTableSummary.selected.indices[0]
    print("Selected Row Index ", str(selectionRowIndex))
    selectionValue=sourceTableSummary.data['Apples'][selectionRowIndex]
    print("Selected value for Apples ", str(selectionValue))
    # selectionColumnIndex?
    # selectionRowHeader?
    # selectionColumnHeader?


sourceTableSummary.on_change('selected', return_value)

curdoc().add_root(column(children=[data_table]))

This gives the following which can returns rows, and the values within the selection. This is ideal if I always want a single column returned. However the selection UI (dotted line) seems to suggest that the specific column is known, not just the row. If there's no way of attaining the selected column, can I look it up using both the Row Index and the Cell Value?

Local Server Output & Table

解决方案

The following code uses JS callback to show the row and column index as well as the cell contents. The second Python callback is a trick to reset the indices so that a click on the same row can be detected (tested with Bokeh v1.0.4). Run with bokeh serve --show app.py

from random import randint
from datetime import date
from bokeh.models import ColumnDataSource, TableColumn, DateFormatter, DataTable, CustomJS
from bokeh.layouts import column
from bokeh.models.widgets import TextInput
from bokeh.plotting import curdoc

source = ColumnDataSource(dict(dates = [date(2014, 3, i + 1) for i in range(10)], downloads = [randint(0, 100) for i in range(10)]))
columns = [TableColumn(field = "dates", title = "Date", formatter = DateFormatter()), TableColumn(field = "downloads", title = "Downloads")]
data_table = DataTable(source = source, columns = columns, width = 400, height = 280, editable = True, reorderable = False)

text_row = TextInput(value = None, title = "Row index:", width = 420)
text_column = TextInput(value = None, title = "Column Index:", width = 420)
text_date = TextInput(value = None, title = "Date:", width = 420)
text_downloads = TextInput(value = None, title = "Downloads:", width = 420)
test_cell = TextInput(value = None, title = "Cell Contents:", width = 420)

source_code = """
var grid = document.getElementsByClassName('grid-canvas')[0].children;
var row, column = '';

for (var i = 0,max = grid.length; i < max; i++){
    if (grid[i].outerHTML.includes('active')){
        row = i;
        for (var j = 0, jmax = grid[i].children.length; j < jmax; j++)
            if(grid[i].children[j].outerHTML.includes('active')) 
                { column = j }
    }
}
text_row.value = String(row);
text_column.value = String(column);
text_date.value = String(new Date(source.data['dates'][row]));
text_downloads.value = String(source.data['downloads'][row]); 
test_cell.value = column == 1 ? text_date.value : text_downloads.value; """

def py_callback(attr, old, new):
    source.selected.update(indices = [])

source.selected.on_change('indices', py_callback)
callback = CustomJS(args = dict(source = source, text_row = text_row, text_column = text_column, text_date = text_date, text_downloads = text_downloads, test_cell = test_cell), code = source_code)
source.selected.js_on_change('indices', callback)
curdoc().add_root(column(data_table, text_row, text_column, text_date, text_downloads, test_cell))

Result:

这篇关于Bokeh DataTable - 在选择回调时返回行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆