2017-05-16 4 views
2

내가 가진 내가 전체의 비율 인쇄를 포맷하고 싶은는 2D NumPy와 배열 플로트 포맷 -> 비율

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

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

같은 2D NumPy와 배열 :

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

나는 herehere에서 몇 가지 해결책을 시도했지만 아직 제대로 작동하지 못했습니다 :

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

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

또 다른 시도 :

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

AttributeError: __exit__ 

답변

1
#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)