如何使用Altair将%添加到熊猫枢轴表中

发布于 2025-02-10 10:23:19 字数 940 浏览 4 评论 0原文

我正在研究调查,并且数据看起来像这样:

ID    Q1    Q2    Q3    Gender    Age    Dept
001   Y      N    Y      F         22     IT
002   N      Y    Y      M         35     HR
003   Y      N    N      F         20     IT
004   Y      N    Y      M         54     OPRE
005   Y      N    Y      M         42     OPRE

所以我创建了一个枢轴表:

Q1    #Respondents      %Res
Y        4               80
N        1               20

如果我想通过性别切片,那么它应该是这样的:

Q1      #Res        %Rep
       M    F      M    F
Y      2    2      50   50
N      1    0      100   0

如果我希望将其应用于所有问题,我想使用Altiar,使我能够选择这个问题,以便我不需要一直执行代码。 到目前为止,我只知道如何创建简单的表:

Q1 = pd.pivot_table(df,values = ['ID'], 
                index = ["Q1"], 
                aggfunc ={'ID': 'count', })
Q1['%Respondents'] = (Q1['ID']/Q1['ID'].sum())*100
Q1

我不知道如何通过性别打破它并应用Altair。 请让我知道您是否可以提供帮助!谢谢!

I am working on a survey and the data looks like this:

ID    Q1    Q2    Q3    Gender    Age    Dept
001   Y      N    Y      F         22     IT
002   N      Y    Y      M         35     HR
003   Y      N    N      F         20     IT
004   Y      N    Y      M         54     OPRE
005   Y      N    Y      M         42     OPRE

So I created a pivot table like this:

Q1    #Respondents      %Res
Y        4               80
N        1               20

If I would like to slice it by Gender, then it should be like:

Q1      #Res        %Rep
       M    F      M    F
Y      2    2      50   50
N      1    0      100   0

And if I want this to be applied to all the questions, I'd like to use Altiar which enables me to choose the question so that I don't need to execute the codes all the time.
So far, I only know how to create simple table by:

Q1 = pd.pivot_table(df,values = ['ID'], 
                index = ["Q1"], 
                aggfunc ={'ID': 'count', })
Q1['%Respondents'] = (Q1['ID']/Q1['ID'].sum())*100
Q1

I don't know how to break it by gender and apply Altair.
Please let me know if you could help! Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

森林迷了鹿 2025-02-17 10:23:19

iiuc,您可以pivot_table,然后将Division的结果添加为新的foo列%受访者

out = df.pivot_table(index='Q1', columns=['Gender'], values=['ID'], aggfunc='count', fill_value=0)
out = (out.join(out[['ID']].div(out['ID'].sum(axis=1).values, axis=0)
                .mul(100)
                .rename(columns={'ID':'%Respondents'})))
print(out)

       ID    %Respondents
Gender  F  M            F      M
Q1
N       0  1          0.0  100.0
Y       2  2         50.0   50.0

IIUC, you can pivot_table then add the result of division as a new foo column %Respondents

out = df.pivot_table(index='Q1', columns=['Gender'], values=['ID'], aggfunc='count', fill_value=0)
out = (out.join(out[['ID']].div(out['ID'].sum(axis=1).values, axis=0)
                .mul(100)
                .rename(columns={'ID':'%Respondents'})))
print(out)

       ID    %Respondents
Gender  F  M            F      M
Q1
N       0  1          0.0  100.0
Y       2  2         50.0   50.0
顾冷 2025-02-17 10:23:19

通过性别打破。只是将其用作索引,然后取消

Q1 = pd.pivot_table(df,values = ['ID'], 
                index = ["Q1","Gender"], 
                aggfunc ={'ID': 'count', }).unstack(level = 0)

堆放的张开,无法帮助您图形

To break by gender. Just utilized it as index, and then unstack it

Q1 = pd.pivot_table(df,values = ['ID'], 
                index = ["Q1","Gender"], 
                aggfunc ={'ID': 'count', }).unstack(level = 0)

Unfurtunataly cant help you with you graph

丢了幸福的猪 2025-02-17 10:23:19

为了保持球的滚动,在这里如何将%添加到Altair图表中。

  • 步骤1。将宽数据框架转换为带有熔体的长框架。
    我制作了一个简单的条形图,其中Q1计数 - 尚无百分比%。
df=pd.DataFrame({'ID':[1, 2, 3, 4, 5],
'Q1':['Y', 'N', 'Y', 'Y', 'Y'],
'Q2':['N', 'Y', 'N', 'N', 'N'],
'Q3':['Y', 'Y', 'N', 'Y', 'Y'],
'Gender':['F', 'M', 'F', 'M', 'M'],
'Age':[22, 35, 20, 54, 42],
'Dept':['IT', 'HR', 'IT', 'OPRE', 'OPRE']}).melt(id_vars=['ID', 'Gender', "Age", "Dept"])

alt.Chart(df.query('variable=="Q1"'), title="Q1").mark_bar().encode(
    x=alt.X('value:N', title="", axis=alt.Axis(labelAngle=0)),
    y=alt.Y('count()', axis=alt.Axis(tickMinStep=1)),
    color="Gender",
    column=alt.Column("Gender", title="")
).properties(width=100, height =150)

  • 步骤2:可能的方案之一 - 如何计算%:
qs=df.variable.unique().tolist()
charts=[]

for q in qs:
    chart=alt.Chart(df.loc[df['variable']==q], title=q).transform_joinaggregate(
        total='count(*)'
        ).transform_calculate(
        pct='1 / datum.total').mark_bar().encode(
            y=alt.Y('value:N', title=""),
            x=alt.X('sum(pct):Q', axis=alt.Axis(format='%'), title=""),
            tooltip=[alt.Tooltip('sum(pct):Q',format=".1%")],
            color="Gender"
        ).properties(width=200)
    charts.append(chart)

alt.hconcat(*charts).configure_scale(
        bandPaddingInner=0.03
    )

”图表,%split”

To keep the ball rolling, here how you could add % into altair charts.

  • Step 1. Convert wide dataframe to a long one with melt.
    I made a simple bar chart with counts for Q1 - without percentage % yet.
df=pd.DataFrame({'ID':[1, 2, 3, 4, 5],
'Q1':['Y', 'N', 'Y', 'Y', 'Y'],
'Q2':['N', 'Y', 'N', 'N', 'N'],
'Q3':['Y', 'Y', 'N', 'Y', 'Y'],
'Gender':['F', 'M', 'F', 'M', 'M'],
'Age':[22, 35, 20, 54, 42],
'Dept':['IT', 'HR', 'IT', 'OPRE', 'OPRE']}).melt(id_vars=['ID', 'Gender', "Age", "Dept"])

alt.Chart(df.query('variable=="Q1"'), title="Q1").mark_bar().encode(
    x=alt.X('value:N', title="", axis=alt.Axis(labelAngle=0)),
    y=alt.Y('count()', axis=alt.Axis(tickMinStep=1)),
    color="Gender",
    column=alt.Column("Gender", title="")
).properties(width=100, height =150)

count chart

  • Step 2: One of possible scenarios - how to calculate %:
qs=df.variable.unique().tolist()
charts=[]

for q in qs:
    chart=alt.Chart(df.loc[df['variable']==q], title=q).transform_joinaggregate(
        total='count(*)'
        ).transform_calculate(
        pct='1 / datum.total').mark_bar().encode(
            y=alt.Y('value:N', title=""),
            x=alt.X('sum(pct):Q', axis=alt.Axis(format='%'), title=""),
            tooltip=[alt.Tooltip('sum(pct):Q',format=".1%")],
            color="Gender"
        ).properties(width=200)
    charts.append(chart)

alt.hconcat(*charts).configure_scale(
        bandPaddingInner=0.03
    )

charts with % split

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文