I have to present the difference between two percentages using Python. For example, the difference between 40% and 41.234% is 1.234 percentage points, or 1.234 pp.
If I wanted to format the increase as a percentage, I would use the format specifier {:.0%}
:
increase = 0.01234
"{:+.3%} ".format(increase)
>>> "+1.234 %"
What I'm looking for
A format specifier that replaces the %
with pp
, like this:
"{some_specifier} ".format(increase)
>>> "+1.234 pp"
What I'm not looking for
I know that I could use f-strings like this
f"{increase * 100:+.3f} pp"
>>> "+1.234 pp"
but I'm specifically looking for a format specifier that I can use with .format()
.
Edit
I realised that a little bit of background may be useful here. In my implementation, the increase
can represent a normal float, integer, percentage or percentage point. In order to get the right representation, I have use a variable-format mapping that looks something like:
format_mapping = {
"var_x": "{:,.0f}", # for large numbers
"var_y": "{:+.3f}", # for small numbers
"var_z": "{:.4%}", # for percentages
}
The variable names represent the column names of a pandas dataframe my_data
, so that I can then apply the formatting to those columns, for the sake of reporting
for var in my_data.columns:
fmt = format_mapping[var]
my_data[var] = pd.Series(fmt.format(value) for value in my_data[var])