[英]NumPy - Iterate over 2D list and print (row,column) index
使用NumPy
和/或Pandas
處理2D
列表時遇到困難:
獲得所有元素的唯一組合的sum
,而無需再次從同一行中選擇(下面的數組應該是81種組合)。
打印組合中每個元素的行和列。
例如:
arr = [[1, 2, 4], [10, 3, 8], [16, 12, 13], [14, 4, 20]]
(1,3,12,20), Sum = 36 and (row, col) = [(0,0),(1,1),(2,1),(3,2)]
(4,10,16,20), Sum = 50 and (row, col) =[(0,2),(1,0),(2,0),(3,2)]
通過創建所有這些組合和求和的方法:這是使用itertools.product
和array-indexing
的矢量化方法 -
from itertools import product
a = np.asarray(arr) # Convert to array for ease of use and indexing
m,n = a.shape
combs = np.array(list(product(range(n), repeat=m)))
out = a[np.arange(m)[:,None],combs.T].sum(0)
樣品運行 -
In [296]: arr = [[1, 2, 4], [10, 3, 8], [16, 12, 13], [14, 4, 20]]
In [297]: a = np.asarray(arr)
...: m,n = a.shape
...: combs = np.array(list(product(range(n), repeat=m)))
...: out = a[np.arange(m)[:,None],combs.T].sum(0)
...:
In [298]: out
Out[298]:
array([41, 31, 47, 37, 27, 43, 38, 28, 44, 34, 24, 40, 30, 20, 36, 31, 21,
37, 39, 29, 45, 35, 25, 41, 36, 26, 42, 42, 32, 48, 38, 28, 44, 39,
29, 45, 35, 25, 41, 31, 21, 37, 32, 22, 38, 40, 30, 46, 36, 26, 42,
37, 27, 43, 44, 34, 50, 40, 30, 46, 41, 31, 47, 37, 27, 43, 33, 23,
39, 34, 24, 40, 42, 32, 48, 38, 28, 44, 39, 29, 45])
記憶效率方法:這是一種方法,沒有創建所有這些組合,而是使用動態broadcasted
總結,哲學很受this other post
啟發 -
a = np.asarray(arr)
m,n = a.shape
out = a[0]
for i in range(1,m):
out = out[...,None] + a[i]
out.shape = out.size # Flatten
您可以使用itertools
product
函數:
from itertools import product
y = [sum(p) for p in product(*arr)]
len(y)
# 81
列表較小的示例:
arr = [[1,2],[3,4],[5,6]]
[sum(p) for p in product(*arr)]
# [9, 10, 10, 11, 10, 11, 11, 12]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.