how to add a row to a pandas dataframe with interval indices

First idea is use margins in crosstab:

ct = pd.crosstab(df['bins_0'], df['bins_1'], margins=True, margins_name='Total')

Your solution – if need new column Total add categories to columns and axis=1 to sum:

ct = pd.crosstab(df['bins_0'], df['bins_1'])
ct.columns = ct.columns.add_categories('Total')
ct['Total'] = ct.sum(axis=1)

Or add DataFrame.loc if need new Total row:

ct = pd.crosstab(df['bins_0'], df['bins_1'])
ct.index= ct.index.add_categories('Total')
ct.loc['Total'] = ct.sum(axis=0)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top