Skip to content
Advertisement

In pandas, how to pivot a dataframe on a categorical series with missing categories?

I have a pandas dataframe with a categorical series that has missing categories.

In the example shown below, group has the categories "a", "b", and "c", but there are no cases of "c" in the dataframe.

JavaScript

The resulting pivoted dataframe has columns a and b. I expected a c column containing all missing value as well.

JavaScript

How can I pivot a dataframe on a categorical series to include columns with all categories, regardless of whether they were present in the original dataframe?

Advertisement

Answer

pd.pivot_table has a dropna argument which dictates dropping or not value columns full of NaNs.

Try setting it to False:

JavaScript
Advertisement