我有数组np.array二维数组
[[8, 12, 5, 2], [12,15, 6,10], [15, 8, 12, 5], [12,15,8,6]]
我想创建另一个二维数组 ,(数组中的每个数字,重复的次数,位置)
(2,1,[1,4]), (5,2,[1,3],[3,4]) ,(6,2,[2,3],[4,4]) , (8,3,[1,1],[3,1],[4,3]) (12,4,[1,2],[2,1],[3,3],[4,1]) ,(15,3,[2,2],[3,1],[4,2])
I'd like to generate comparisons between rows and columns.
进行解释(以15号为例)
重复:3
位置:[2,2],[3,1],[4,2]
答案 0 :(得分:1)
这是使用np.unqiue
和np.where
的一种方法,请注意numpy
array
中的索引是从0开始而不是1
x,y=np.unique(a.ravel(), return_counts=True)
l=[]
for v,c in zip(x,y):
l.append((v,c,np.column_stack(np.where(a==v)).tolist()))
l
Out[344]:
[(2, 1, [[0, 3]]),
(5, 2, [[0, 2], [2, 3]]),
(6, 2, [[1, 2], [3, 3]]),
(8, 3, [[0, 0], [2, 1], [3, 2]]),
(10, 1, [[1, 3]]),
(12, 4, [[0, 1], [1, 0], [2, 2], [3, 0]]),
(15, 3, [[1, 1], [2, 0], [3, 1]])]
答案 1 :(得分:0)
使用帖子Most efficient way to sort an array into bins specified by an index array?中的代码作为模块stb
,我们可以做到
import numpy as np
from stb import sort_to_bins_sparse as sort_to_bins
from pprint import pprint
X = np.array([[8, 12, 5, 2], [12,15, 6,10], [15, 8, 12, 5], [12,15,8,6]])
unq, inv, cnt = np.unique(X, return_inverse=True, return_counts=True)
sidx = sort_to_bins(inv, np.arange(X.size))
# or (slower but avoids dependency on stb module)
# sidx = np.argsort(inv, kind='stable')
pprint(list(zip(unq, cnt, np.split(np.transpose(np.unravel_index(sidx, X.shape)) + 1, cnt[:-1].cumsum()))))[(2, 1, array([[1, 4]])),
# (5, 2, array([[1, 3],
# [3, 4]])),
# (6, 2, array([[2, 3],
# [4, 4]])),
# (8, 3, array([[1, 1],
# [3, 2],
# [4, 3]])),
# (10, 1, array([[2, 4]])),
# (12, 4, array([[1, 2],
# [2, 1],
# [3, 3],
# [4, 1]])),
# (15, 3, array([[2, 2],
# [3, 1],
# [4, 2]]))]