熊猫系列重复 n 次并更改列值

Tec*_*ech 5 python pandas

我有这样的输入数据。

NAME | PLACE | DATE
  A  |   X   | 2020-04-30
  B  |   Y   | 2019-04-30
Run Code Online (Sandbox Code Playgroud)

我想复制 5 次并通过增加年数来更改日期

NAME | PLACE | DATE
  A  |   X   | 2020-04-30
  A  |   X   | 2021-04-30
  A  |   X   | 2022-04-30
  A  |   X   | 2023-04-30
  A  |   X   | 2024-04-30
  A  |   X   | 2025-04-30
  B  |   Y   | 2019-04-30
  B  |   Y   | 2020-04-30
  B  |   Y   | 2021-04-30
  B  |   Y   | 2022-04-30
  B  |   Y   | 2023-04-30
  B  |   Y   | 2024-04-30
Run Code Online (Sandbox Code Playgroud)

这可以使用熊猫重复吗?。

Shu*_*rma 4

使用:

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)
Run Code Online (Sandbox Code Playgroud)

细节:

创建需要添加到列中以获得所需年份偏移量np.array的对象。DateOffsetDate

print(y)
array([<DateOffset: years=0>, <DateOffset: years=1>,
       <DateOffset: years=2>, <DateOffset: years=3>,
       <DateOffset: years=4>, <DateOffset: years=5>,
       <DateOffset: years=0>, <DateOffset: years=1>,
       <DateOffset: years=2>, <DateOffset: years=3>,
       <DateOffset: years=4>, <DateOffset: years=5>], dtype=object)
Run Code Online (Sandbox Code Playgroud)

用于reindex根据需要重新索引数据框,并使用 allocate 添加Date年份。

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
Run Code Online (Sandbox Code Playgroud)