pandas series repeat n time and change column value

前端 未结 4 1366
半阙折子戏
半阙折子戏 2021-01-13 03:14

I have input data like this.

NAME | PLACE | DATE
  A  |   X   | 2020-04-30
  B  |   Y   | 2019-04-30

i want to duplicate 5 times and change d

4条回答
  •  天涯浪人
    2021-01-13 03:56

    Use:

    df['Date'] = pd.to_datetime(df['Date'])
    
    y = np.array([pd.offsets.DateOffset(years=_) for _ in np.tile(range(6), len(df.index))])
    df = df.reindex(df.index.repeat(6)).assign(Date=lambda x: x['Date'] + y)
    

    Details:

    Create a np.array of DateOffset objects that needs to be added to the Date column to get the desired year offset.

    print(y)
    array([, ,
           , ,
           , ,
           , ,
           , ,
           , ], dtype=object)
    

    Use reindex to reindex the dataframe as required and use assign to add the Date with the years.

    print(df)
      Name Place       Date
    0    A     X 2020-04-30
    0    A     X 2021-04-30
    0    A     X 2022-04-30
    0    A     X 2023-04-30
    0    A     X 2024-04-30
    0    A     X 2025-04-30
    1    B     Y 2019-04-30
    1    B     Y 2020-04-30
    1    B     Y 2021-04-30
    1    B     Y 2022-04-30
    1    B     Y 2023-04-30
    1    B     Y 2024-04-30
    

提交回复
热议问题