Search code examples
pythonnumpymultidimensional-arrayconcatenation

how can i add zero at the fist and end of all an array


I have an array like this:

contact_map = array([[1., 1., 1., ..., 1., 1., 1.],
   [1., 1., 1., ..., 1., 1., 1.],
   [1., 1., 1., ..., 1., 1., 1.],
   ...,
   [0., 0., 0., ..., 0., 0., 0.],
   [0., 0., 0., ..., 0., 0., 0.],
   [0., 0., 0., ..., 0., 0., 0.]])

which each element of that is something like this:

contact_map[19] = array([1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 0., 1., 1., 1., 1., 1.,
   1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 0.,
   0., 0., 0., 0., 0., 1., 0., 1., 1., 1., 1., 0., 0., 1., 1., 0., 0.,
   0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 0., 0., 0., 0., 1., 1., 0.,
   1., 1., 0., 0., 0., 1., 1., 0., 1., 0., 0., 0., 1., 1., 1., 1., 1.,
   1., 0., 1., 0., 0., 0., 0., 1., 0., 0., 1., 0., 1., 1., 1.])

len(contact_map) = 224

len(contact_map[19]) =100

I want to change all elements of contact_map in such a way to add "0" at the first and end of each element, for example changing contact_map[19] into:

contact_map[19] = array([0.,1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 0., 1., 1., 1., 1., 1.,
   1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 0.,
   0., 0., 0., 0., 0., 1., 0., 1., 1., 1., 1., 0., 0., 1., 1., 0., 0.,
   0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 0., 0., 0., 0., 1., 1., 0.,
   1., 1., 0., 0., 0., 1., 1., 0., 1., 0., 0., 0., 1., 1., 1., 1., 1.,
   1., 0., 1., 0., 0., 0., 0., 1., 0., 0., 1., 0., 1., 1., 1., 0,.])

len(contact_map[19]) = 102

and so on, for contact_map[0], contact_map[1], ....

can anyone help me out?


Solution

  • You can use numpy.pad like below:

    >>> import numpy as np
    >>> a = np.array([[1., 1., 1. , 1., 1., 1.],
                      [1., 1., 0. , 0., 1., 1.], 
                      [0., 1., 0. , 0., 1., 1.]])
    >>> a.shape
    (3, 6)
    
    >>> out = np.pad(a, [(0,0), (1, 1)], 'constant', constant_values=0)  
    # pad first dimension ^^^    ^^^
    #                            ^^^ pad second dimension 
    #                                (first num for set how many pad at first
    #                                 second num for ... at last.)                 
    >>> out.shape
    (3,8)
    
    >>> out
    array([[0., 1., 1., 1., 1., 1., 1., 0.],
           [0., 1., 1., 0., 0., 1., 1., 0.],
           [0., 0., 1., 0., 0., 1., 1., 0.]])
    

    Your Input:

    contact_map = np.random.randint(0,2 , (224, 100))
    print(len(contact_map))
    # 224
    print(len(contact_map[19]))
    # 100
    contact_map = np.pad(contact_map, [(0,0), (1, 1)], 'constant', constant_values=0)
    print(len(contact_map[19]))
    # 102
    print(len(contact_map[0]))
    # 102