Skip to main content
 首页 » 编程设计

python之如何创建基于 bins 的矩阵

2024年10月01日7zhenyulu

我有一组 3-27 的值,它们有 20 个有限值:

A = [(0,21),(1,12),(2,15),(3,3),(4,21),(5,15),(6,27),(7,21),(8,9),(9,27),(10,12),(11,9),(12,12),(13,3),(14,9),(15,12),(16,6),(17,3),(18,9),(19,15)] 

我想学习如何创建一个有 9 个 bin 的 numpy 数组,对于给定的元组 [1],每个 bin 的范围为 -1 和 +1 整数,范围为 3- 的 3 的倍数27(但这应该可以与任何其他整数和范围的组合互换)。最后,我希望能够创建一个如下所示的矩阵:

[[0,0,0,0,0,0,1,0,0], 
 [0,0,0,1,0,0,0,0,0], 
 [0,0,0,0,1,0,0,0,0], 
 [1,0,0,0,0,0,0,0,0], 
 [0,0,0,0,0,0,1,0,0], 
 [0,0,0,0,1,0,0,0,0], 
 [0,0,0,0,0,0,0,0,1], 
 ....] 

我正在阅读有关 numpy 如何具有 (num, bins) = histogram(x, bins=None, range=None) 的内容,但我不太确定如何进行。

我在想,我必须遍历“A”以获得唯一值(“a”),然后按 (a-1,a+1) 计算范围,以获得我想要的 bin 数量只是到 len(unique_values)。但后来我迷路了。谁能指导我?

请您参考如下方法:

这是使用 np.searchsorted/np.digitize 的一种方法 -

bins = np.arange(3,28,3) 
ar = np.asarray(A)[:,1] # or np.array([i[1] for i in A]) 
ids = np.searchsorted(bins, ar) # or np.digitize(ar,bins)-1 
out = (ids[:,None] == np.arange(9)).astype(int) 

获取最终输出的最后一步可以用数组初始化代替-

out = np.zeros((len(ids), 9),dtype=int) 
out[np.arange(len(ids)), ids] = 1 

如果元组中的第一个元素不按顺序,我们可能希望使用它们来索引行 -

out[np.asarray(A)[:,0], ids] = 1 

sample 运行-

In [205]: A 
Out[205]:  
[(0, 21), 
 (1, 12), 
 (2, 15), 
 (3, 3), 
 (4, 21), 
 (5, 15), 
 (6, 27), 
 (7, 21), 
 (8, 9), 
 (9, 27), 
 (10, 12), 
 (11, 9), 
 (12, 12), 
 (13, 3), 
 (14, 9), 
 (15, 12), 
 (16, 6), 
 (17, 3), 
 (18, 9), 
 (19, 15)] 
 
In [206]: out[:7] # first 7 rows of output 
Out[206]:  
array([[0, 0, 0, 0, 0, 0, 1, 0, 0], 
       [0, 0, 0, 1, 0, 0, 0, 0, 0], 
       [0, 0, 0, 0, 1, 0, 0, 0, 0], 
       [1, 0, 0, 0, 0, 0, 0, 0, 0], 
       [0, 0, 0, 0, 0, 0, 1, 0, 0], 
       [0, 0, 0, 0, 1, 0, 0, 0, 0], 
       [0, 0, 0, 0, 0, 0, 0, 0, 1]])