I have a Dataframe like

A%  B %
2   3
-   2.1
100 0
-   5

i want the output exported excel to be like

A%        B%
2.00%     3.00%
-         2.10%
100.00%   0.00%
-         5.00%

I have these A% and B% by using the following logic

((df['some_values1'] / df['some_values2']) *100.00).round(2).astype(str)+('%')

but when i make the excel of the df the - get converted to nan and the single digits like 2, 100, 0 does not have two decimals like 2.00% 100.00% & 0.00% it is 2%,100% and 0% only whereas it works fine with 2.1 and other fractional digits.

Thanks in advance for any help.

1

There are 1 best solutions below

6
On

You can define a function that suits your needs:

def to_percent_format(p):
    if str(p).strip() != "-":
        return "{:.2%}".format(p/100)
    else:
        return p.strip() 

Indeed:

>>> to_percent_format(3)
'3.00%'
>>> to_percent_format("-")
'-'

And just apply it to your dataframe!

df.apply(to_percent_format, axis=1)