如何向列添加月份并根据 pandas 中的频率创建多个列

问题描述 投票:0回答:1

我下面有一个 DF

DF

ID  name    qty price   date      Freq
1   abc     20   3   17/01/2022    4
1   abc     10   5   18/03/2022    3
2   def     10   7   24/01/2022    1
2   def     40   2   25/05/2022    6
3   ghi    322   7   4/5/2022      12

我的期望是按月添加频率到日期列并预测 12 个月。 和多个数量,价格作为 Amt 列,并显示项目月份的相同值。

预期产出 enter image description here

我尝试过的解决方案 DF['col1'] = DF.apply(lambda x:x['date'] + pd.offsets.DateOffset(months=x['Freq']),1). 我知道上面的查询只是增加了几个月,但我需要将其投影为 12 个月,如预期输出中所述。

注 1 - Col5 一直到 col12,因为我预测了 12 个月。

python pandas dataframe numpy data-manipulation
1个回答
0
投票

您可以转换

to_datetime
,然后使用
DateOffset
添加多个月份:

df['Amt'] = df['qty']*df['price']
df['col1'] = (pd.to_datetime(df['date'], dayfirst=True)
                .add(pd.DateOffset(months=1)*df['Freq'])
                .pipe(lambda s: pd.to_datetime(s).dt.strftime('%d/%m/%Y'))
             )

输出:

   ID name  qty  price        date  Freq   Amt        col1
0   1  abc   20      3  17/01/2022     4    60  17/05/2022
1   1  abc   10      5  18/03/2022     3    50  18/06/2022
2   2  def   10      7  24/01/2022     1    70  24/02/2022
3   2  def   40      2  25/05/2022     6    80  25/11/2022
4   3  ghi  322      7    4/5/2022    12  2254  04/05/2023
© www.soinside.com 2019 - 2024. All rights reserved.