【问题标题】:vectorized assignment statement for selected elements of 2d array in numpynumpy中二维数组的选定元素的矢量化赋值语句
【发布时间】:2012-10-31 05:42:12
【问题描述】:

我是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

如果你是一个一维数组,这样的分配工作,但我无法弄清楚如何使这个工作为二维数组工作。 您的建议将是最有帮助的。 谢谢

【问题讨论】:

    标签: python arrays numpy indexing vectorization


    【解决方案1】:

    你快到了。

    你需要的是:

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

    解释:

    既然你说你是 Python 的初学者(我也是!),我想我可以告诉你这个;它被认为是 unpythonic 以您的方式加载模块:

    #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_index (row_col_index[0]) 的第一个数组用于 rows,将第二个数组 (row_col_index[1]) 用于列.

    最后,如果你不使用ipython,我建议你这样做,它将在学习过程和许多其他事情上为你提供帮助。

    我希望这会有所帮助。

    【讨论】:

    • 感谢您提供详细的答案和最佳实践提示。我一直试图用 row_col_index 数组作为一个整体进行索引而不提取行。
    • 不客气。你能选这个作为正确答案吗?
    猜你喜欢
    • 2018-01-24
    • 2018-01-09
    • 1970-01-01
    • 2014-08-06
    • 2017-12-17
    • 2021-01-14
    • 2011-12-31
    • 2015-06-16
    • 2018-01-14
    相关资源
    最近更新 更多