Home > Back-end >  Duplicate same rows n times with new week
Duplicate same rows n times with new week

Time:01-06

Every week I need to upload a new week with the same data as the prior.

For example, this is what I have:

    import pandas as pd  
    data = {'Date': ['02/01/2023', '02/01/2023', '02/01/2023', '02/01/2023']
            , 'Where': ['Spain', 'Spain', 'France', 'France']
            , 'Metric': ['Holiday', 'Holiday', 'Expected', 'Expected']
            , 'Value': [1, 0, 10, 5]}  
    df = pd.DataFrame(data)  
    print(df)  
Date Where Metric Value
02/01/2023 Spain Holiday 1
02/01/2023 Spain Holiday 0
02/01/2023 France Expected 10
02/01/2023 France Expected 5

This is what I need:

Date Where Metric Value
02/01/2023 Spain Holiday 1
02/01/2023 Spain Holiday 0
02/01/2023 France Expected 10
02/01/2023 France Expected 5
09/01/2023 Spain Holiday 1
09/01/2023 Spain Holiday 0
09/01/2023 France Expected 10
09/01/2023 France Expected 5

So, basically taking the same data from above but adding one week to the last date.

This is what I have so far... it's incomplete (not copying the data) and I don't know how to continue:

  from datetime import timedelta, date

  def daterange(start_date, end_date):
  for n in range(0, int((end_date - start_date).days)   1, 7):
     yield start_date   timedelta(n)

 start_dt = date(2023, 01, 02) '''These needs to be dynamic: last date available'''
 end_dt = date(2023, 01, 02)

Thank you!

CodePudding user response:

Use append, groupby and tail e.g.

df.Date = pd.to_datetime(df.Date)  
rows = (df.groupby(list(df.columns)).tail(1))
rows.Date = pd.to_datetime(rows.Date)   pd.DateOffset(days=7)
df.append(rows)

Out[87]: 
        Date   Where    Metric  Value
0 2023-02-01   Spain   Holiday      1
1 2023-02-01   Spain   Holiday      0
2 2023-02-01  France  Expected     10
3 2023-02-01  France  Expected      5
0 2023-02-08   Spain   Holiday      1
1 2023-02-08   Spain   Holiday      0
2 2023-02-08  France  Expected     10
3 2023-02-08  France  Expected      5
  • Related