【问题标题】:Formatting a 2D Numpy Array Float -> Percentage格式化 2D Numpy 数组浮点数 -> 百分比
【发布时间】:2017-05-16 04:17:26
【问题描述】:

我有一个 2D numpy 数组,例如

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

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

我想将其格式化为打印总数的百分比:

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__

【问题讨论】:

    标签: python numpy string-formatting


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2020-09-05
      • 2019-10-03
      • 2014-01-27
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多