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

cf2*_*cf2 5 python arrays numpy list

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

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])]
Run Code Online (Sandbox Code Playgroud)

现在我使用集合来计算出现次数,它返回集合的列表。计数器:

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})]
Run Code Online (Sandbox Code Playgroud)

我正在寻找的结果是一个包含 3 列的数组,表示值 0 到 2 和行的 len(listvalues)。每个单元格都应填充该值在数组中出现的百分比:

# Result
66.66    0      33.33
0        50     50
33.33    0      66.66
Run Code Online (Sandbox Code Playgroud)

因此,0 在数组 1 中出现 66.66%,在数组 2 中出现 0%,在数组 3 中出现 33.33%,依此类推。

实现这一目标的最佳方法是什么?非常感谢!

Div*_*kar 3

这是一个方法 -

# 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])
Run Code Online (Sandbox Code Playgroud)

在输入列表中使用额外的第四个数组运行示例 -

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]]
Run Code Online (Sandbox Code Playgroud)