Pandas Pivot table- Column to remain even the value is '0' for all index

Viewed 36

I was new to pandas and I was manipulating a CSV file to create the pivot table.

The base file used consists of all orders pending in our system. I have categorized the order based on the age_Cate and pivoted the result.

Result expected:

Result expected

The row index is the different order types and the column is the age group. the value is the count of the order pending.

code used to create the above table.

#OFFLINE ORDER - R - pivoted based on order_cate as row , age group as columns & line_number as values (counted)
df_pivot_qty =df_plain_R.pivot_table(values="line_num",index=["order_Cate"],columns="age_Group",aggfunc = "count",fill_value = 0,dropna = False ,margins=True,margins_name="Total").sort_values(['0-4','5-7','8-10','11-15','16-21','22-31','>31',"Total"])[['0-4','5-7','8-10','11-15','16-21','22-31','>31','Total']]
df_pivot_qty

The problem is if there is no order pending in the category '>31' - the table not getting formed.

if I remove the sort values command the table appears but the column index is not in order.

1 Answers

If you want the pivot table column to appear even when the column value is zero or Not available

change the data type of the column to category type

Related