我有这样的输入数据。
NAME | PLACE | DATE
A | X | 2020-04-30
B | Y | 2019-04-30
我想复制 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
这可以使用 Pandas 重复吗?。
最佳答案
使用:
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)
详情:创建一个
np.array
的 DateOffset
需要添加到Date
的对象列以获得所需的年份偏移量。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)
使用 reindex
根据需要重新索引数据框并使用assign添加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
关于python - Pandas 系列重复 n 次并更改列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63085302/