在 Python 中,有没有一种方法可以根据双列分组 table 中的第一列创建条形图?

In Python is there a way to create a bar chart based on the first column in a two-column groupby table?

我想根据双列分组中的第一列创建条形图 table。我通过应用 groupby 来创建我想要的 table 来总结我的数据框。我的 groupby table 目前只有两列,第一列是类别,第二列是我的数据框中这些类别的计数。我想使用第一列作为 x 轴,然后使用第二列作为 y 轴来创建一个带有 plotly express 的条形图。但是,当我将 groupby 应用于数据框时,它按照我想要的方式对数据进行了分组,但第一列没有标签。为了创建条形图,我需要明确地告诉 x 轴是什么,但是 groupby table.

中没有标签

这是我目前为我的 groupby table:

# Selection list

department = df['Provider Type'].unique().tolist()

departments_selection = st.multiselect('Program:',
                                        department,
                                        default=department)

# Filter dataframe based on selection

mask = df['Provider Type'].isin(departments_selection)
number_of_result = df[mask].shape[0]
st.markdown(f'*Available Results: {number_of_result}*')

## Booked
df_grouped = df[mask].groupby(['Provider Type'])['Provider Type'].count()
st.dataframe(df_grouped)

这是我想要的输出:

如您所见,第一列没有标签,因此我在尝试创建条形图时无法引用它。所以当我真的只想使用第一列的类别作为标签时,我最终得到了一个只有数字作为标签的条形图。这是我的:

# Bar chart
pie_chart = px.bar(df_grouped,
                x="Provider Type",
                y='Provider Type',
                template='plotly_white')

st.plotly_chart(pie_chart)

这是输出:

有人可以帮我修复我的 x 轴,以便它显示像我的 groupby table 中的类别吗?我只是不确定如何告诉它查找第一列,因为它没有标签。

您可以将 x 参数传递给 px.bar df_grouped.index

因为问题中没有提供数据,所以我无法进行分组,但此代码示例应向您展示如何修复 x 轴标签:

import pandas as pd
import plotly.express as px


d = {'Provider Type': [340, 861, 446, 148, 1484, 953, 347, 615]}
index = ['Community Health navigation', 'Dietitian', 'Kinesiology', 
         'MH Navigation', 'MH Therapist', 'Nursing', 'Pharmacist', 'Specialist']
df = pd.DataFrame(data=d, index=index)

fig = px.bar(df, y='Provider Type', x=df.index)
fig.show()

输出: