[英]How to sample a huge 2D array in Python using 2x2 arrays to create a dictionary? (Stencil Algorithm for Python)
我是編程的新手,如果這是一個經典而瑣碎的問題,我深表歉意。 我有一個100x100
2D值數組,可通過matplotlib
繪制。 在此圖像中,每個單元格都有其值(范圍為0.0
到1.0
)和ID(范圍為0
到9999
從左上角開始)。 我想使用產生兩個字典的2x2移動窗口對矩陣進行采樣:
在下面的示例( 左上圖 )中,N的ID = 0,第一個字典將產生{'0': (0,1,100,101)}
因為單元格的編號分別是:右側的0到99和0到9900 ,步進= 100,向下。 第二個字典將產生{'0': 0.775}
,因為0.775是N的四個相鄰單元的平均值。當然,這些字典必須具有與2D數組上的“交集”一樣多的鍵。
如何做到這一點? 在這種情況下,詞典是最好的“工具”嗎? 感謝大伙們!
PS:我嘗試了自己的方式,但是我的代碼不完整,錯誤,並且無法解決:
a=... #The 2D array which contains the cell values ranging 0.0 to 1.0
neigh=numpy.zeros(4)
mean_neigh=numpy.zeros(10000/4)
for k in range(len(neigh)):
for i in a.shape[0]:
for j in a.shape[1]:
neigh[k]=a[i][j]
...
好吧,字典實際上可能就是您的情況。
您確定使用的numpy.array格式正確嗎? 我在API中找不到任何array((int,int))形式。 無論如何...
聲明2D數組后該怎么辦
為了使事情井井有條,讓我們做兩個可以與任何正方形2D數組一起使用的函數,返回您需要的兩個字典:
#this is the one that returns the first dictionary
def dictionarize1(array):
dict1 = {}
count = 0
for x in range(len(array[0]) - 1) :
for y in range(len(array[0]) - 1):
dict1[count] = [array[x][y], array[x][y+1], array[x+1][y], array[x + 1][y+1]]
count = count + 1
return dict1
def dictionarize2(array):
dict2 = {}
counter = 0
for a in range(len(array[0]) - 1) :
for b in range(len(array[0]) - 1):
dict2[counter] = (array[a][b] + array[a][b+1] + array[a+1][b] + array[a + 1][b+1])/4
counter = counter + 1
return dict2
#here's a little trial code to see them working
eighties = [[2.0, 2.2, 2.6, 5.7, 4.7], [2.1, 2.3, 2.3, 5.8, 1.6], [2.0, 2.2, 2.6, 5.7, 4.7],[2.0, 2.2, 2.6, 5.7, 4.7],[2.0, 2.2, 2.6, 5.7, 4.7]]
print("Dictionarize1: \n")
print(dictionarize1(eighties))
print("\n\n")
print("Dictionarize2: \n")
print(dictionarize2(eighties))
print("\n\n")
與第一個代碼相比,我更喜歡使用整數作為鍵,因為python將打印在這種情況下排序的字典(字典按定義是未排序的,但是如果它們具有int鍵,Python將按鍵將其打印出來)。 但是,您可以像以前一樣使用str(count)將其更改回字符串。
我希望這會有所幫助,因為我現在對數學庫不是很實用,但是我編寫的代碼應該可以與您要輸入的任何2D方陣一起很好地工作!
假設data
是原始的numpy.array
,行和列的維度為dr
和dc
。
dr = data.shape[0]
dc = data.shape[1]
您可以將Keys
成為一個函數,該函數返回感興趣的索引和Values
作為具有4個相鄰像元的計算平均值的列表。 在這種情況下, Keys
等於:
def Keys(x):
xmod = x + (x+1)/dc # dc is in scope
return [xmod, xmod + 1, xmod + dc, xmod + 1 + dc]
因為不包括最后一行和最后一列,所以“ Values
”的維等於dr-1 * dc-1
。 我們可以將其計算為移動平均值,然后再調整為1D
(來自link的啟發):
Values = ((d[:-1,:-1] + d[1:,:-1] + d[:-1,1:] + d[1:,1:])/4).reshape((dr-1)*(dc-1))
例:
dr = 3
dc = 5
In: np.array(range(dc*dr)).reshape((dr, dc)) # data
Out:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
In: [Keys(x) for x in range((dr-1)*(dc-1))]
Out:
[[0, 1, 5, 6],
[1, 2, 6, 7],
[2, 3, 7, 8],
[3, 4, 8, 9],
[5, 6, 10, 11],
[6, 7, 11, 12],
[7, 8, 12, 13],
[8, 9, 13, 14]]
In: Values
Out: array([ 3, 4, 5, 6, 8, 9, 10, 11])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.