您如何找到 Numpy 数组中有多少百分比具有某个值 X?

How can you find what percentage of a Numpy Array has some value X?

假设我有一个 numpy 数组:

array = np.array(['Fe', 'Pt', 'Ce', 'Nd', 'Pt', 'Fe', ..., 'Pt', 'Ce', 'Fe', 'Fe'])

数组中的每个条目是 'Fe'、'Pt'、'Ce' 或 'Nd'。我了解如何获取单个条目的百分比,例如:

percentage = np.sum(array = 'Fe')/array.shape[0]*100

但是如果我想获取每个唯一字符串值的百分比怎么办?有没有办法将该操作向量化并将其泛化为任意数量的唯一字符串值?

理想情况下,我想要这样的东西:

percentages = np.some_operation(array)

产生如下输出:

percentages = {'Fe': 25, 'Pt': 15, 'Nd': 45, 'Ce': 15}

不一定要是字典的形式,只要明确哪个百分比属于哪个元素即可。我打算处理的数组的长度可能在 1,000 到 1,000,000 之间。

只需使用 np.unique 中的 return_counts 参数即可:

uniques, counts = np.unique(array, return_counts=True)

然后从您的 2 个数组创建字典:

percentages = dict(zip(uniques, counts * 100 / len(array)))

替代np.unique,您可以使用collections.Counter

import numpy as np
from collections import Counter

arr = np.array(['Fe', 'Pt', 'Ce', 'Nd', 'Pt', 'Fe', 'Pt', 'Ce', 'Fe', 'Fe'])
ln = arr.shape[0]

cnt = Counter(arr)
ans = {i: cnt[i]*100/ln for i in cnt}

print(ans)

输出:

{'Fe': 36.36363636363637, 'Pt': 27.272727272727273, 'Ce': 18.181818181818183, 'Nd': 9.090909090909092}

我用谷歌搜索了一下,找到了这个答案 你可以这样做:

import numpy as np

array = np.array(['Fe', 'Pt', 'Ce', 'Nd', 'Pt', 'Fe', 'Pt', 'Ce', 'Fe', 'Fe'])
percentage = {i:np.sum(array == i)/array.shape[0]*100 for i in array}

print(percentage)