Search code examples
pythonpandasdataframepython-datetime

how to duplicate pandas datetime object


I have a a 1X1 pandas Series object which contains a single datetime object. I want to duplicate this row into additional X rows (eg 10). I have tried doing it through the .append command as well as plain multiplication but it does not seem to work when the object type is 'datetime'. Help appreciated.

>>> print df
0   2016-04-21
dtype: datetime64[ns]

the desired output should be something like (which I generated through rather cumbersome df.append([df,df,df...])

0   2016-04-21
0   2016-04-21
0   2016-04-21
0   2016-04-21
0   2016-04-21
0   2016-04-21
dtype: datetime64[ns]

Solution

  • you can use numpy.tile() function for that:

    In [43]: s = pd.Series(pd.to_datetime('2016-04-21'))
    
    In [44]: s
    Out[44]:
    0   2016-04-21
    dtype: datetime64[ns]
    
    In [45]: np.tile(s, 10)
    Out[45]:
    array(['2016-04-21T02:00:00.000000000+0200',
           '2016-04-21T02:00:00.000000000+0200',
           '2016-04-21T02:00:00.000000000+0200',
           '2016-04-21T02:00:00.000000000+0200',
           '2016-04-21T02:00:00.000000000+0200',
           '2016-04-21T02:00:00.000000000+0200',
           '2016-04-21T02:00:00.000000000+0200',
           '2016-04-21T02:00:00.000000000+0200',
           '2016-04-21T02:00:00.000000000+0200',
           '2016-04-21T02:00:00.000000000+0200'], dtype='datetime64[ns]')
    
    In [46]: pd.DataFrame(np.tile(s, 10), columns=['date'])
    Out[46]:
            date
    0 2016-04-21
    1 2016-04-21
    2 2016-04-21
    3 2016-04-21
    4 2016-04-21
    5 2016-04-21
    6 2016-04-21
    7 2016-04-21
    8 2016-04-21
    9 2016-04-21