如何基于多筛选条件在同工作表中并排展示数据视图
多筛选条件组合与数据视图并排展示方案
需求背景
我已经基于多种条件生成了大量表格,现在需要通过多个筛选条件将数据并排展示,想搞清楚怎么在表格里应用/组合多筛选条件,从而在同一份脚本里生成不同的数据视图。
现有脚本(已修正语法错误)
原脚本存在列表括号闭合错误和拼写问题,修正后如下:
df = df[(df.category == 'Pant1') | (df.category == 'Pant2')] def create_summary_tables(df): white = df[df['color']=='White'].shape[0] blue = df[df['color']=='Blue'].shape[0] black = df[df['color']=='Black'].shape[0] green = df[df['color']=='Green'].shape[0] pant = pd.DataFrame([ ['White', white, round((white / df.shape[0]) * 100, 2)], ['Blue', blue, round((blue / df.shape[0]) * 100, 2)], ['Black', black, round((black / df.shape[0]) * 100, 2)], ['Green', green, round((green / df.shape[0]) * 100, 2)] ], columns=['Color', 'Sum', 'Percent']) return pant
预期效果
要生成多组并排的汇总表格,每组表格对应不同的筛选条件(比如顶部高亮栏分别对应不同品类、尺码等维度),每组表格都展示对应筛选结果下各颜色的数量和占比,实现多数据视图的并列展示。
实现方案
1. 把筛选和统计逻辑做成通用函数
不用重复写统计代码,把筛选条件作为参数传入,让函数能适配不同条件生成对应表格:
def create_filtered_summary(df, filter_condition): # 应用筛选条件得到子数据集 filtered_df = df[filter_condition] # 自动统计各颜色的数量 color_counts = filtered_df['color'].value_counts().reset_index() color_counts.columns = ['Color', 'Sum'] # 计算占比并保留两位小数 color_counts['Percent'] = round((color_counts['Sum'] / filtered_df.shape[0]) * 100, 2) # 确保所有目标颜色都在表格中(避免筛选后某些颜色缺失,用0填充) target_colors = ['White', 'Blue', 'Black', 'Green'] color_counts = color_counts.set_index('Color').reindex(target_colors).fillna(0).reset_index() return color_counts
2. 定义多组筛选条件
根据需求灵活组合条件,示例如下:
# 筛选条件1:仅Pant1品类 filter_pant1 = df['category'] == 'Pant1' # 筛选条件2:仅Pant2品类 filter_pant2 = df['category'] == 'Pant2' # 筛选条件3:Pant1且尺码为M filter_pant1_m = (df['category'] == 'Pant1') & (df['size'] == 'M') # 筛选条件4:所有品类中价格大于100的商品 filter_price_over_100 = df['price'] > 100
组合条件用&(且)、|(或)、~(非),注意多条件需用括号包裹。
3. 生成多视图并并排展示
用IPython的HTML展示功能实现表格并排,或用可视化工具美化:
import pandas as pd from IPython.display import display_html # 生成各个筛选条件下的表格 table_pant1 = create_filtered_summary(df, filter_pant1) table_pant2 = create_filtered_summary(df, filter_pant2) table_pant1_m = create_filtered_summary(df, filter_pant1_m) # 定义并排展示函数 def show_side_by_side(dfs, titles): html_content = '' for df, title in zip(dfs, titles): # 每个表格独立成块,设置间距 html_content += f''' <div style="display: inline-block; margin: 0 20px;"> <h4>{title}</h4> {df.to_html(index=False, border=1)} </div> ''' display_html(html_content, raw=True) # 调用函数展示三组表格 show_side_by_side( [table_pant1, table_pant2, table_pant1_m], ['Pant1 汇总', 'Pant2 汇总', 'Pant1-M码 汇总'] )
4. 方案优势
- 复用性强:同一函数适配所有筛选条件,无需重复编写统计逻辑
- 扩展性好:新增筛选条件仅需定义新的
filter_condition,调用函数即可生成对应视图 - 易维护:统计逻辑修改时,仅需调整通用函数,不用逐个修改表格生成代码
内容的提问来源于stack exchange,提问作者user19840753
相关产品推荐
相关产品推荐

