Crosstab() function
import numpy as np
import pandas as pd
p = np.array(["s1", "s1", "s1", "s1", "b1", "b1",
"b1", "b1", "s1", "s1", "s1"], dtype=object)
q = np.array(["one", "one", "one", "two", "one", "one",
"one", "two", "two", "two", "one"], dtype=object)
r = np.array(["x", "x", "y", "x", "x", "y",
"y", "x", "y", "y", "y"],
dtype=object)
pd.crosstab(p, [q, r], rownames=['p'], colnames=['q', 'r'])
Here ‘r’ and ‘s’ are not represented in the data and will not be shown in the output because dropna is True by default.
Set dropna=False to preserve categories with no data.
s1 = pd.Categorical(['p', 'q'], categories=['p', 'q', 'r'])
b1 = pd.Categorical(['s', 't'], categories=['s', 't', 'u'])
pd.crosstab(s1, b1)
pd.crosstab(s1, b1, dropna=False)