Numpy 二维数组获取总数的百分比

Numpy 2D array get percentage of total

我刚开始使用 numpy..

得到以下 np table 并想计算每个单元格占列总数的百分比。

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) 会给我总计,但我如何使用它来计算数组。

数组的大小可以变化...

你可以试试这个。在 axis = 0 上使用 numpy.sum 并在轴 0.

上用总和划分数组 data
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%']]