You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Bokeh中CDSView过滤后的元素数量及行索引?

获取Bokeh中CDSView过滤后的元素数量与原索引

Bokeh的CDSView本身不会直接返回过滤后的结果,但因为你使用的是BooleanFilter,且多个过滤器是逻辑与的关系(必须同时满足所有过滤条件),可以手动计算所有过滤条件的交集,得到和视图一致的过滤结果,进而获取元素数量和原索引。

实现步骤

  • 计算所有布尔过滤条件的交集,生成最终的掩码数组
  • 从掩码中提取符合条件的原索引,元素数量就是索引列表的长度

修改后的示例代码

from bokeh.models import BooleanFilter, CDSView, ColumnDataSource
from bokeh.plotting import figure, show

source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5]))
booleansX = [True if x_val < 5 else False for x_val in source.data['x']]
booleansY = [True if y_val > 1 else False for y_val in source.data['y']]
view = CDSView(source=source, filters=[BooleanFilter(booleansX), BooleanFilter(booleansY)])

# 计算所有过滤条件的交集(逻辑与)
combined_mask = [x and y for x, y in zip(booleansX, booleansY)]
# 获取过滤后元素在原CDS中的索引
filtered_indices = [idx for idx, keep in enumerate(combined_mask) if keep]
# 获取过滤后的元素数量
filtered_count = len(filtered_indices)

print(f"过滤后的元素数量: {filtered_count}")
print(f"过滤后元素的原索引: {filtered_indices}")

p_filtered = figure(height=300, width=300)
p_filtered.circle(x="x", y="y", size=10, source=source, view=view)

show(p_filtered)

运行结果

运行后会输出:

过滤后的元素数量: 3
过滤后元素的原索引: [1, 2, 3]

这和你预期的3行结果一致,且索引对应原ColumnDataSource中符合x<5且y>1的行(x=2,3,4;y=2,3,4)。

内容的提问来源于stack exchange,提问作者e5k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 00:12:12