簡體   English   中英

在 for 循環中替換數組列的值 Python

[英]Replace the values of a column of an array in a for loop Python

我有一個 3D 零數組,我想使用 for 循環替換第二列和第三列的元素。 在 matlab 中,我創建了一個零矩陣並填充它,但在 python 中,我不明白我該怎么做。

我嘗試了以下方式:

U=np.zeros((3,150,150))
step=10
A=[rows,columns]
jj=0
    for j in range(1,columns+1,step):
        jj=jj+1 #jj total = 184
    

         ii=0
         for i in range(1,rows+1,step):        
             ii=ii+1  #ii total = 154


             U[:,0,1]=ii,jj

這樣,我得到一個數組 U,其中第二列和第三列的每個值都有最后一個 ii 和 jj 的值。

相反,我希望數組 A 中存在的每個像素(i,j)按照定義的步驟逐步替換為數組 U 的第二列和第三列。 你有什么想法嗎?

最后,數組 U 的大小為 (3x154x184)

此代碼將在 for 循環中將 A 的值放入 U。 如果您有其他邏輯要使用,您可以將其添加到跳過的行中。

import numpy as np

columns = 150
rows = 150
step=1
A=np.random.randint(100, size=(columns,rows))
U=np.zeros((3,columns,rows))

jj=0
for j in range(0,columns,step):
    jj=jj+1 #jj total = 184
    
    
    ii=0
    for i in range(0,rows,step):        
        ii=ii+1  #ii total = 154
        
        U[:,ii-1,jj-1]=A[i,j]

print(U)

如果這就是您想要完成的全部,您可以像這樣更簡單地完成它:

U[:]=A

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM