python - 计算数组列表的计数百分比

标签 python arrays list numpy

简单的问题,但我似乎无法让它工作。我想计算一个数字在数组列表中出现的百分比并相应地输出这个百分比。 我有一个数组列表,如下所示:

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/

相关文章:

python - 用python拟合直方图

python - OrderedDict 键错误

ruby-on-rails - Array.count 在本地工作正常但在 heroku 上中断

python - 应用于可迭代对象的每个元素的 bool 语句分支

javascript - 如何创建一个动态列表,其中的元素描述仅在单击元素时显示?

通过 SSH 隧道连接到 Namecheap 的 MySQL 数据库的 Python 脚本

Python:我想做一个连续命名文件的截图脚本

python - 如何处理字符串列表,其中每个字符串也可能是逗号分隔的字符串列表?

mysql - 如何使用数组对Mysql结果集进行排序

JavaScript 数组长度不正确