![](/img/trans.png)
[英]Is there a way to find the indices of an entire row of numbers in a 2D array in Python?
[英]python search and find specify numbers location in array 2d
我有數組 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]
這是使用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]])]
使用這篇文章中的代碼將數組排序到索引數組指定的 bin 的最有效方法? 作為模塊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]]))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.