Search code examples
pythonarraysnumpyrepeattile

How to repeat a series of numbers with shape (n,1) as an array of n unique numbers repeated by 4 times with a shape of (n,1)


I think this is a relatively straightfoward question but I've been struggling with getting this to the right shape. I have a series/dataframe column structured as:

0         0.127883
1         0.129979
2         0.130000
            ...   
1000   0.090000

I want to turn this into:

[[array([0.12788259, 0.12788259, 0.12788259, 0.12788259])]
 [array([0.12997902, 0.12997902, 0.12997902, 0.12997902])]
 [array([0.13, 0.13, 0.13, 0.13])]
 ...
 [array([0.09, 0.09, 0.09, 0.09])]
 [array([0.09, 0.09, 0.09, 0.09])]
 [array([0.09, 0.09, 0.09, 0.09])]]

Essentially, I am trying to create a matrix with shape (n,1) containing the input number repeated by 4 times, but wrapped in an array. I have only been able to get to the following:

arr_out = np.array(np.tile(np.array(a).reshape(-1,1),4))

and the corresponding result, which while looks the same, is missing the comma in between variables and without the 'array' wrapper:

     [[1.12788259 1.12788259 1.12788259 1.12788259]
     [1.12997902 1.12997902 1.12997902 1.12997902]
     [1.13       1.13       1.13       1.13      ]
     ...
     [1.09       1.09       1.09       1.09      ]
     [1.09       1.09       1.09       1.09      ]
     [1.09       1.09       1.09       1.09      ]]

Thank you in advance!


Solution

  • How about this method:

    import numpy as np
    ser = np.arange(5, dtype = float) # Edit: added argument 'dtype = float'
    arr = ser.repeat(4).reshape(-1, 4)
    l = list(arr)
    ob_arr = np.array([None for i in range(len(l))], dtype = object)
    for i in range(len(ob_arr)):
        ob_arr[i] = l[i]
    

    output:

    array([array([0., 0., 0., 0.]), array([1., 1., 1., 1.]),
           array([2., 2., 2., 2.]), array([3., 3., 3., 3.]),
           array([4., 4., 4., 4.])], dtype=object)