我正在尝试获取 numpy 3d 数组中每个子数组的频率计数(不含零)。但是,scipy.stats.itemfreq 工具返回二维数组中的频率计数。
我得到的是:
array_3d= array([[[1, 0, 0],
[1, 0, 0],
[0, 2, 0]],
[[0, 0, 0],
[0, 0, 3],
[3, 3, 3]],
[[0, 0, 4],
[0, 0, 4],
[0, 0, 4]]])
>>> itemfreq(array_3d)[1:,]
# outputs
array([ 1, 2],
[ 2, 1],
[ 3, 4],
[ 4, 3]], dtype=int64)
虽然我想要输出:
array([[ 1, 2, 2, 1],
[ 3, 4],
[ 4, 3]], dtype=object)
想法是奇数总是唯一值,偶数是频率。
另一个输出可能是:
array([ 1, 2, 0],
[ 2, 1, 0],
[ 3, 4, 1],
[ 4, 3, 2]], dtype=int64)
其中第三列表示三维数组中的子集编号。
我也对其他输出/解决方案持开放态度!
提前致谢!
请您参考如下方法:
numpy_indexed包(免责声明:我是它的作者)可以用来以优雅和矢量化的方式解决这个问题:
import numpy_indexed as npi
index = np.arange(array_3d.size) // array_3d[0].size
(value, index), count = npi.count((array_3d.flatten(), index))
然后给出:
index = [0 0 0 1 1 2 2]
value = [0 1 2 0 3 0 4]
count = [6 2 1 5 4 6 3]
如果需要,可以通过使用 > 0 的索引进行后处理
