简单的问题,但我似乎无法让它工作。我想计算一个数字在数组列表中出现的百分比并相应地输出这个百分比。 我有一个数组列表,如下所示:
import numpy as np
# Create some data
listvalues = []
arr1 = np.array([0, 0, 2])
arr2 = np.array([1, 1, 2, 2])
arr3 = np.array([0, 2, 2])
listvalues.append(arr1)
listvalues.append(arr2)
listvalues.append(arr3)
listvalues
>[array([0, 0, 2]), array([1, 1, 2, 2]), array([0, 2, 2])]
现在我使用集合计算出现次数,它返回一个集合列表。计数器:
import collections
counter = []
for i in xrange(len(listvalues)):
counter.append(collections.Counter(listvalues[i]))
counter
>[Counter({0: 2, 2: 1}), Counter({1: 2, 2: 2}), Counter({0: 1, 2: 2})]
我要查找的结果是一个包含 3 列的数组,代表 0 到 2 的值和行的 len(listvalues)。每个单元格应填充数组中出现的该值的百分比:
# Result
66.66 0 33.33
0 50 50
33.33 0 66.66
因此 0 在数组 1 中出现 66.66%,在数组 2 中出现 0%,在数组 3 中出现 33.33%,依此类推。
实现此目标的最佳方法是什么? 非常感谢!
最佳答案
这是一种方法-
# Get lengths of each element in input list
lens = np.array([len(item) for item in listvalues])
# Form group ID array to ID elements in flattened listvalues
ID_arr = np.repeat(np.arange(len(lens)),lens)
# Extract all values & considering each row as an indexing perform counting
vals = np.concatenate(listvalues)
out_shp = [ID_arr.max()+1,vals.max()+1]
counts = np.bincount(ID_arr*out_shp[1] + vals)
# Finally get the percentages with dividing by group counts
out = 100*np.true_divide(counts.reshape(out_shp),lens[:,None])
在输入列表中使用额外的第四个数组运行示例 -
In [316]: listvalues
Out[316]: [array([0, 0, 2]),array([1, 1, 2, 2]),array([0, 2, 2]),array([4, 0, 1])]
In [317]: print out
[[ 66.66666667 0. 33.33333333 0. 0. ]
[ 0. 50. 50. 0. 0. ]
[ 33.33333333 0. 66.66666667 0. 0. ]
[ 33.33333333 33.33333333 0. 0. 33.33333333]]
关于python - 计算数组列表的计数百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38504737/