Reverse part of an array using NumPy

前端 未结 3 442
-上瘾入骨i
-上瘾入骨i 2020-12-19 21:41

I am trying to use array slicing to reverse part of a NumPy array. If my array is, for example,

a = np.array([1,2,3,4,5,6])

then I can get

相关标签:
3条回答
  • 2020-12-19 22:12

    If you don't like the off by one indices

    >>> a = np.array([1,2,3,4,5,6])
    >>> a[1:4] = a[1:4][::-1]
    >>> a
    array([1, 4, 3, 2, 5, 6])
    
    0 讨论(0)
  • 2020-12-19 22:15

    You can use the permutation matrices (that's the numpiest way to partially reverse an array).

    a = np.array([1,2,3,4,5,6])
    new_order_for_index = [1,4,3,2,5,6] # Careful: index from 1 to n !
    
    # Permutation matrix
    m = np.zeros( (len(a),len(a)) )
    for index , new_index  in enumerate(new_order_for_index ):
        m[index ,new_index -1] = 1
    
    print np.dot(m,a)
    # np.array([1,4,3,2,5,6])
    
    0 讨论(0)
  • 2020-12-19 22:31
    >>> a = np.array([1,2,3,4,5,6])
    >>> a[1:4] = a[3:0:-1]
    >>> a
    array([1, 4, 3, 2, 5, 6])
    
    0 讨论(0)
提交回复
热议问题