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

如何编写Python函数批量执行value_counts并绘制分组柱状图减少重复代码

解决方案

第一步:封装分组统计函数

先把重复的分组频次统计逻辑封装为可复用函数,同时提前统一处理字符串格式的空值:

import pandas as pd
import plotly.graph_objects as go

# 先把数据中字符串格式的空值转换为pandas识别的NaN,避免统计到无效空值
waste_priority = waste_priority.replace(['NAN', 'NaN'], pd.NA)

def group_count(df, group_col, count_cols):
    """
    按指定列分组后,批量统计多列的取值频次
    参数:
        df: 原始数据集
        group_col: 分组依据的列名,此处为'Q7a'
        count_cols: 需要统计频次的列名列表,此处为Q8系列列
    返回:
        统计结果列表,每个元素对应一列的统计结果
    """
    result = []
    for col in count_cols:
        count_df = df.groupby(group_col)[col].value_counts().reset_index(name='counts')
        result.append(count_df)
    return result

第二步:封装分组柱状图绘图函数

将重复的绘图逻辑也封装为函数,后续调整参数即可快速修改图表:

def plot_group_bar(count_df_list, legend_names, title="Waste prioty per Estate", x_col='Q7a', y_col='counts'):
    """
    批量生成分组柱状图的各个系列,统一配置布局
    参数:
        count_df_list: 分组统计结果列表,和图例名称一一对应
        legend_names: 每个柱状系列的图例展示名称
        title: 图表标题
        x_col: x轴取值对应的列名
        y_col: y轴取值对应的列名
    返回:
        配置完成的Figure对象
    """
    fig = go.Figure()
    # 循环添加所有柱状系列,无需重复写多遍go.Bar
    for count_df, legend_name in zip(count_df_list, legend_names):
        fig.add_trace(go.Bar(
            name=legend_name,
            x=count_df[x_col],
            y=count_df[y_col],
            text=count_df[y_col],
            textposition='auto'
        ))
    # 统一设置图表布局
    fig.update_layout(
        title_text=title,
        barmode='group',
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=1.02,
            xanchor="right",
            x=1
        )
    )
    return fig

调用示例

只需要修改列名和图例名称列表,即可快速完成统计和绘图,后续新增列也只需在列表中添加对应元素即可:

# 定义需要统计的Q8系列列,以及对应的图例名称
q8_columns = ['Q8a', 'Q8b', 'Q8c', 'Q8d']
legend_names = ['Littering smells and looks bad', 'Effect on human health', 'Effect on environment', 'Others']

# 批量统计
waste_priority_list = group_count(waste_priority, group_col='Q7a', count_cols=q8_columns)

# 绘图并展示
fig = plot_group_bar(waste_priority_list, legend_names)
fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:54:03