1

I need to convert floating point numbers in a pd.DataFrame into strings and add the percentage sign.

So far, I am using the following lines of code:

import numpy as np
import pandas as pd

df = pd.DataFrame(data=np.random.randn(5,5)).round(2).astype(str) + "%"

print(df)

        0       1      2       3       4
0   0.01%  -0.24%  -0.2%  -1.72%  -0.11%
1  -0.16%  -3.18%  -1.5%  -0.57%    2.0%
2   0.69%   0.13%  1.14%  -0.76%   0.59%
3   0.05%  -0.98%  0.87%   1.72%  -0.82%
4  -1.32%   0.21%  1.04%   0.28%  -0.03%

How can I make sure, that I always print EXACTLY two digits?

Andi
  • 3,196
  • 2
  • 24
  • 44
  • 5
    `df = pd.DataFrame(data=np.random.randn(5,5)).applymap('{:.2%}'.format)`? Not overly fast, though there is not a vectorized answer to this problem. [How do I edit the string format of several Pandas DataFrame float columns?](https://stackoverflow.com/q/69598829/15497888) – Henry Ecker Oct 18 '21 at 14:13

0 Answers0