2

I have a 2D numpy array like

x = np.array([[3,3],[3,1]])

Out[107]: 
array([[3, 3],
       [3, 1]])

I would like to format it to print percentages of the total:

array([['33.3%', '33.3%'],
       ['33.3%', '10.0%']]

I've tried some solutions from here and here but have yet to get these to work:

pct_formatter = lambda x: "{:.2%}".format(x/x.sum() * 100 )
pct_formatter(x)

TypeError: non-empty format string passed to object.__format__

another attempt:

with np.set_printoptions(formatter=pct_formatter):
    print(pct_formatter(x))

AttributeError: __exit__
Community
  • 1
  • 1
Max Power
  • 8,265
  • 13
  • 50
  • 91

1 Answers1

3
#user a dataframe to format the numbers and then convert back to a numpy array.
pd.DataFrame(x/float(np.sum(x))).applymap(lambda x: '{:.2%}'.format(x)).values
Out[367]: 
array([['30.00%', '30.00%'],
       ['30.00%', '10.00%']], dtype=object)
Allen Qin
  • 19,507
  • 8
  • 51
  • 67