【问题标题】:can numpy interpret column of indices like matlab doesnumpy可以像matlab一样解释索引列吗
【发布时间】:2013-10-08 05:02:39
【问题描述】:
 mat = nan (5,4)

mat =

   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN

fact = rand(5,4)

fact =

    0.3507    0.5870    0.8443    0.4357
    0.9390    0.2077    0.1948    0.3111
    0.8759    0.3012    0.2259    0.9234
    0.5502    0.4709    0.1707    0.4302
    0.6225    0.2305    0.2277    0.1848

cd =

     1
     5
     2
     3
     4

>> mat(cd, : ) = fact

mat =

    0.3507    0.5870    0.8443    0.4357
    0.8759    0.3012    0.2259    0.9234
    0.5502    0.4709    0.1707    0.4302
    0.6225    0.2305    0.2277    0.1848
    0.9390    0.2077    0.1948    0.3111

在 python 或 numpy 中是否有类似的东西可以完成最后一行的基本操作,即您可以输入一列索引,它会自动用相应的行填充 nan 矩阵,而不是遍历它并执行这一行手动按行。

还注意到 cd 可以有比 mat 更多的行,并且 mat 可以自行相应地扩展,至少 matlab 可以。

【问题讨论】:

    标签: python matlab numpy


    【解决方案1】:

    您可以在 python 中完全做到这一点,只需使用基于 0 的索引而不是基于 1 的索引:

    >>> m[cd-1] = fact
    
    >>> m 
    array([[ 0.3507,  0.587 ,  0.8443,  0.4357],
           [ 0.8759,  0.3012,  0.2259,  0.9234],
           [ 0.5502,  0.4709,  0.1707,  0.4302],
           [ 0.6225,  0.2305,  0.2277,  0.1848],
           [ 0.939 ,  0.2077,  0.1948,  0.3111]])
    

    【讨论】:

      【解决方案2】:

      我认为它的工作原理几乎相同:

      >>> arr = np.empty((5,4))
      >>> arr.fill(np.nan)
      >>> arr
      array([[ nan,  nan,  nan,  nan],
             [ nan,  nan,  nan,  nan],
             [ nan,  nan,  nan,  nan],
             [ nan,  nan,  nan,  nan],
             [ nan,  nan,  nan,  nan]])
      >>> rand = np.random.random((5,4))
      >>> rand
      array([[ 0.10378825,  0.36936186,  0.65145694,  0.79532325],
             [ 0.69595542,  0.78740795,  0.31969862,  0.81173803],
             [ 0.06674611,  0.99920068,  0.78696773,  0.01768565],
             [ 0.9948402 ,  0.34200073,  0.60993921,  0.13801365],
             [ 0.18503791,  0.39392016,  0.64800295,  0.98816382]])
      >>> cd = [0, 4, 1, 2, 3]   # Numpy arrays are 0-indexed.
      >>> arr[cd, :] = rand
      >>> arr
      array([[ 0.10378825,  0.36936186,  0.65145694,  0.79532325],
             [ 0.06674611,  0.99920068,  0.78696773,  0.01768565],
             [ 0.9948402 ,  0.34200073,  0.60993921,  0.13801365],
             [ 0.18503791,  0.39392016,  0.64800295,  0.98816382],
             [ 0.69595542,  0.78740795,  0.31969862,  0.81173803]])
      

      【讨论】:

      • @ali_m -- 我想我应该在我把脚放进嘴里之前测试一下......谢谢:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 2018-11-21
      • 2011-07-12
      • 1970-01-01
      • 2012-03-03
      • 2019-03-09
      • 1970-01-01
      相关资源
      最近更新 更多