Home > Enterprise >  Repeat a pandas DataFrame by datetime rows
Repeat a pandas DataFrame by datetime rows

Time:03-09

I have a pandas DataFrame and a datetime column by month. I am wondering how to assign the DataFrame to each date so each date will have the same repeated DataFrame.

DataFrame:

data = {'product_name': ['laptop', 'printer', 'tablet', 'desk', 'chair'],
        'price': [1200, 150, 300, 450, 200]
        }

df = pd.DataFrame(data, index=['a123','a518','a608','a790','a890'])

     product_name  price
a123       laptop   1200
a518      printer    150
a608       tablet    300
a790         desk    450
a890        chair    200

and dates:

pd.DataFrame(pd.date_range(start='2020-07', end='2025-07', freq='M'))

            0
0  2020-07-31
1  2020-08-31
2  2020-09-30
3  2020-10-31
4  2020-11-30
..        ...
56 2025-03-31
57 2025-04-30
58 2025-05-31
59 2025-06-30
60 2025-07-31

CodePudding user response:

You could repeat the index reindex with it multiplicate and assign the dates to a new column sort (optional):

dates = pd.date_range(start='2020-07', end='2025-07', freq='M')
df = (df.reindex(df.index.repeat(len(dates)))
      .assign(date=dates.tolist()*len(df))
      .rename_axis('').sort_values(by=['date','']).rename_axis(None))

Output:

     product_name  price       date
a123       laptop   1200 2020-07-31
a518      printer    150 2020-07-31
a608       tablet    300 2020-07-31
a790         desk    450 2020-07-31
a890        chair    200 2020-07-31
...           ...    ...        ...
a123       laptop   1200 2025-06-30
a518      printer    150 2025-06-30
a608       tablet    300 2025-06-30
a790         desk    450 2025-06-30
a890        chair    200 2025-06-30

[300 rows x 3 columns]
  • Related