【问题标题】:Numpy 2D array get percentage of totalNumpy 2D 数组占总数的百分比
【发布时间】:2020-09-05 08:26:06
【问题描述】:

我刚开始使用 numpy..

得到下面的 np 表,并想计算每个单元格在列总数中的百分比。

data = np.array([[7,16,17], [12,11,3]])
headers = ["Grundskola", "Gymn", "Akademisk"]

# tabulate data
table = tabulate(data, headers, tablefmt="github")

# output
print(table)

|   Grundskola |   Gymn |   Akademisk |
|--------------|--------|-------------|
|            7 |     16 |          17 |
|           12 |     11 |           3 |

到:

|   Grundskola |   Gymn |   Akademisk |
|--------------|--------|-------------|
|           39%|    59% |         85% |
|           61%|    41% |         15% |

我知道 np.sum(data2, axis=0/1) 会给我总数,但我如何使用来计算数组。

数组的大小可以不同...

【问题讨论】:

    标签: python python-3.x numpy percentage numpy-ndarray


    【解决方案1】:

    你可以试试这个。在 axis = 0 上使用 numpy.sum 并将数组 data 与轴 0 上的总和相除。

    data = np.array([[7, 16, 17],
                     [12, 11, 3]])
    
    percentages = data/data.sum(axis=0) * 100
    
    percentages
    # array([[36.84210526, 59.25925926, 85.        ],
    #        [63.15789474, 40.74074074, 15.        ]])
    

    现在,在tabulate 函数中使用这个percentages


    您可以将mini string language 格式化为如下格式。

    perc = data / data.sum(axis=0)
    # array([[0.36842105, 0.59259259, 0.85      ],
    #        [0.63157895, 0.40740741, 0.15      ]])
    
    print(np.array([[f"{i:.2%}" for i in val] for val in perc]))
    # [['36.84%' '59.26%' '85.00%']
    #  ['63.16%' '40.74%' '15.00%']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      相关资源
      最近更新 更多