Python - Pandas crosstab() - formatting call values?

not sure if possible, but it would be good if I could apply a percentage format to cells resulting from pd.crosstab(), as I am using the normalize='columns' option.
They are percentage results, so displaying as percentages would be nice.

Can it be done?

Or perhaps a different crosstab function exists where it can be done?

I searched everywhere but couldn't find anything, but that doesn't mean it's impossible (perhaps!)
Many thanks.


Solution 1:

The pd.crosstab() gives you the right results.

foo = pd.Categorical(['a', 'b', 'a', 'a'], categories=['a', 'b', 'c'])
bar = pd.Categorical(['d', 'e', 'e', 'd'], categories=['d', 'e', 'f'])
result = pd.crosstab(foo, bar, normalize='columns')

If you just want to display them with percentages, you could use style formatters:

result.style.format("{:.0%}")

Which should produce this output:

col_0   d       e
row_0        
a       100%    50%
b       0%      50%