Efficient way to add a singleton dimension to a NumPy vector so that slice assignments work

前端 未结 5 869
清歌不尽
清歌不尽 2020-12-11 00:48

In NumPy, how can you efficiently make a 1-D object into a 2-D object where the singleton dimension is inferred from the current object (i.e. a list should go to either a 1x

相关标签:
5条回答
  • 2020-12-11 00:56

    What about expand_dims?

    np.expand_dims(np.array([1,2,3,4]), 0)
    

    has shape (1,4) while

    np.expand_dims(np.array([1,2,3,4]), 1)
    

    has shape (4,1).

    0 讨论(0)
  • 2020-12-11 01:00

    Why not simply add square brackets?

    >> my_list
    [1, 2, 3, 4]
    >>> numpy.asarray([my_list])
    array([[1, 2, 3, 4]])
    >>> numpy.asarray([my_list]).shape
    (1, 4)
    

    .. wait, on second thought, why is your slice assignment failing? It shouldn't:

    >>> my_list = [1,2,3,4]
    >>> d = numpy.ones((3,4))
    >>> d
    array([[ 1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.]])
    >>> d[0,:] = my_list
    >>> d[1,:] = numpy.asarray(my_list)
    >>> d[2,:] = numpy.asarray([my_list])
    >>> d
    array([[ 1.,  2.,  3.,  4.],
           [ 1.,  2.,  3.,  4.],
           [ 1.,  2.,  3.,  4.]])
    

    even:

    >>> d[1,:] = (3*numpy.asarray(my_list)).T
    >>> d
    array([[  1.,   2.,   3.,   4.],
           [  3.,   6.,   9.,  12.],
           [  1.,   2.,   3.,   4.]])
    
    0 讨论(0)
  • 2020-12-11 01:00
    import numpy as np
    a = np.random.random(10)
    sel = np.at_least2d(a)[idx]
    
    0 讨论(0)
  • 2020-12-11 01:16

    In the most general case, the easiest way to add extra dimensions to an array is by using the keyword None when indexing at the position to add the extra dimension. For example

    my_array = numpy.array([1,2,3,4])
    
    my_array[None, :] # shape 1x4
    
    my_array[:, None] # shape 4x1
    
    0 讨论(0)
  • 2020-12-11 01:16

    You can always use dstack() to replicate your array:

    import numpy
    
    my_list = array([1,2,3,4])
    my_list_2D = numpy.dstack((my_list,my_list));
    
    0 讨论(0)
提交回复
热议问题