如何在python的dataframe中给定的日期上添加灵活的年数?

如何在python的dataframe中给定的日期上添加灵活的年数?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据框 sec date l1 l2 0 abc 2001-03-27 12 31 1 abc 2001-03-29 13 32 2 abc 2001-04-03 14 33 3 abc 2001-05-04 15 34 4 abc 2001-07-05 16 35 5 abc 2001-07-06 17 36 6 abc 2001-08-07 18 37 7 abc 2001-09-08 19 3

我有一个数据框

    sec    date     l1  l2 
0   abc 2001-03-27  12  31
1   abc 2001-03-29  13  32
2   abc 2001-04-03  14  33
3   abc 2001-05-04  15  34
4   abc 2001-07-05  16  35
5   abc 2001-07-06  17  36
6   abc 2001-08-07  18  37
7   abc 2001-09-08  19  38
8   abc 2001-10-09  20  39
9   abc 2001-11-10  21  40
10  abc 2001-12-11  22  41
我想写一个函数,它有两个参数,比如flexible_date_adder(data,no_of_years_to_add=[1,4])

期望值:如果我通过我的数据框,我将得到两列名为“date1yr”和“date4yr”,这两列将在我的日期上加上1年和4年,并给出结果

预期输出:

    sec    date     l1  l2  date1yr      date4yr   
0   abc  2001-03-27 12  31  2002-03-27  2005-03-27
用于所有数据帧日期。
谢谢

试试:

df.date = pd.to_datetime(df.date)

def flexible_date_adder(data, no_of_years_to_add):
    add_year = {}
    for y in no_of_years_to_add:
         add_year[f"year{y}"] = (data.date+pd.DateOffset(years=y))
    return (add_year)

no_of_years_to_add=[1,4]
df = pd.concat([df,pd.DataFrame(df.apply(flexible_date_adder, no_of_years_to_add=[1,4], axis=1).tolist())],axis=1)

df:

    sec    date     l1  l2  date1yr      date4yr   
0   abc  2001-03-27 12  31  2002-03-27  2005-03-27
秒 日期 l1 l2 第一年 第四年 0 abc 2001-03-27 12 31 2002-03-27 2005-03-27 1. abc 2001-03-29 13 32 2002-03-29 2005-03-29 2. abc 2001-04-03 14 33 2002-04-03 2005-04-03 3. abc 2001-05-04 15 34 2002-05-04 2005-05-04 4. abc 2001-07-05 16 35 2002-07-05 2005-07-05 5. abc 2001-07-06 17 36 2002-07-06 2005-07-06 6. abc 2001-08-07 18 37 2002-08-07 2005-08-07 7. abc 2001-09-08 19 38 2002-09-08 2005-09-08 8. abc 2001-10-09 20 39 2002-10-09 2005-10-09 9 abc 2001-11-10 21 40 2002-11-10 2005-11-10 10 abc 2001-12-11 22 41 2002-12-11 2005-12-11
虽然有点晚,但我将以这种方式对其进行编码,让函数处理所有事情:

def flexible_date_adder(df1, no_of_years_to_add=None):
    if no_of_years_to_add is None:
        no_of_years_to_add = [1, 4]
 
    for year in no_of_years_to_add:
        df1[f'date{year}yr'] = df1['date'] + pd.DateOffset(years=year)

    return df1
试运行: 另请注意: 正如我看到您在示例函数布局中为list参数设置了默认列表一样,我添加了这个旁注供您参考

永远不要在函数参数处为列表参数提供默认列表。将其设置为None,并改为在函数内部初始化。否则,当函数多次运行时,“可变默认值”将导致不可预测的错误

例如:

    def something(x=[]):
        x.append(1)
        print (x)

    >>> something()
    [1]

    >>> something()
    [1, 1]

    >>> something()
    [1, 1, 1]

这回答了你的问题吗?