簡體   English   中英

numpy中2d數組的選定元素的矢量化賦值語句

[英]vectorized assignment statement for selected elements of 2d array in numpy

我是python的初學者。 我想知道是否有一種不使用for循環的“好”方式來執行此操作。 考慮問題

u = zeros((4,2))
u_pres = array([100,200,300])
row_col_index = array([[0,0,2], [0,1,1]])

我想將u [0,0],u [0,1]和u [2,1]分別指定為100,200和300。 我想做某種形式的事情

u[row_col_index] = u_pres

如果u是一維數組,則這樣的分配有效,但無法弄清楚如何使此數組適用於二維數組。 您的建議將最有幫助。 謝謝

你快到了。

您需要以下內容:

u[row_col_index[0], row_col_index[1]] = u_pres

說明:

既然您說您是Python的初學者(我也是!),我想我可能會告訴您這一點。 以這種方式加載模塊被認為是非Python的

#BAD
from numpy import *
#GOOD
from numpy import array #or whatever it is you need
#GOOD
import numpy as np #if you need lots of things, this is better

說明:

In [18]: u = np.zeros(10)

In [19]: u
Out[19]: array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

#1D assignment
In [20]: u[0] = 1

In [21]: u[1] = 10

In [22]: u[-1] = 9 #last element

In [23]: u[-2] = np.pi #second last element

In [24]: u
Out[24]: 
array([  1.        ,  10.        ,   0.        ,   0.        ,
         0.        ,   0.        ,   0.        ,   0.        ,
         3.14159265,   9.        ])

In [25]: u.shape
Out[25]: (10,)

In [27]: u[9] #calling
Out[27]: 9.0

#2D case
In [28]: y = np.zeros((4,2))

In [29]: y
Out[29]: 
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])

In [30]: y[1] = 10 #this will assign all the second row to be 10

In [31]: y
Out[31]: 
array([[  0.,   0.],
       [ 10.,  10.],
       [  0.,   0.],
       [  0.,   0.]])

In [32]: y[0,1] = 9 #now this is 2D assignment, we use 2 indices!

In [33]: y[3] = np.pi #all 4th row, similar to y[3,:], ':' means all

In [34]: y[2,1] #3rd row, 2nd column
Out[34]: 0.0


In [36]: y[2,1] = 7

In [37]: 

In [37]: y
Out[37]: 
array([[  0.        ,   9.        ],
       [ 10.        ,  10.        ],
       [  0.        ,   7.        ],
       [  3.14159265,   3.14159265]])

在您的情況下,我們將row_col_indexrow_col_index[0] )的第一個數組用於 ,將第二個數組( row_col_index[1] )用於列。

最后,如果您不使用ipython ,我建議您這樣做,它將在學習過程和其他許多方面幫助您。

我希望這有幫助。

暫無
暫無

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

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