有没有办法在 Pandas python 中获得具有多个列的交叉表(频率 table)中的总计列

Is there a way to get a Total column in crosstab (frequency table) with multiple columns in Pandas python

我的副索引 (Center_Name) 旁边需要一个 总计列 。交叉表中有边距功能,但仅限于一列。我有以下代码在交叉表中有多个列,但无法添加总列。

我正在使用的代码(从 Excel 导出数据):

cols=['Gender','QAge_Post']
q2=(nb.melt(id_vars='Center_Name',value_vars=cols)
       .groupby([pd.Grouper(key='Center_Name'),'value'])
       .size()
       .unstack(fill_value=0))
q2

我有 50 行,列 Center_Name,性别,QAge_Post。我使用 Center_name 作为索引,其余两个作为列。

输出:

Center_Name 18 - 25 Years 26 - 35 years Male Female
Delhi 8 5 3 10
Kolkata 2 6 4 4
Lucknow 7 5 5 7
Mumbai 0 11 2 9
Pune 3 3 5 1

最后我还需要总行

对新行 sum 使用 DataFrame.insert with select only Male and Female columns for sum and also DataFrame.loc

df.insert(0, 'Total', df[['Male','Female']].sum(axis=1))
df.loc['Total'] = df.sum()
print (df)
             Total  18 - 25 Years  26 - 35 years  Male  Female
Center_Name                                                   
Delhi           13              8              5     3      10
Kolkata          8              2              6     4       4
Lucknow         12              7              5     5       7
Mumbai          11              0             11     2       9
Pune             6              3              3     5       1
Total           50             20             30    19      31