AttributeError:“系列”对象没有属性“ isoweekday”

时间:2019-12-11 14:21:35

标签: python pandas dataframe attributeerror

我编写了一个函数,该函数相对于周末和节假日将日期移动指定的工作日数。当我将其与标量值一起使用时,它可以正常工作,但是尝试在pandas DataFrame上使用时遇到问题。 该函数本身如下所示:

def move_date_by_days(init_date, roll=1, nwd_key=None, hol_key=None):
    '''
    moves date by n-number of working days forward or backward
    init_date: date, initial caluclation date
    roll: integer, number of days to move forward (+) or backward (-)
    nwd_key: string that stands for currency iso code, it is a key in non_working_days dictionary
    hol_key: string that stands for currency iso code, it is a key in holidays dictonary
    return: date
    '''
    nwd = non_working_days.get(nwd_key, [])
    hol = holidays.get(hol_key,[])
    moved_date = init_date + datetime.timedelta(days=roll)
    if (moved_date.isoweekday() in nwd) or (moved_date in hol):
        if roll >= 0:
            moved_date=move_date_by_days(init_date + datetime.timedelta(days=1), roll=roll, nwd_key=nwd_key, hol_key=hol_key)
        else:
            moved_date=move_date_by_days(init_date + datetime.timedelta(days=-1), roll=roll, nwd_key=nwd_key, hol_key=hol_key)
    return moved_date

现在,我的数据框为'df',列为'start_date'和'end_date'

   start_date    end_date
0  2020-01-31  2020-04-30
1  2020-04-30  2020-07-31
2  2020-07-31  2020-10-31
3  2020-10-31  2020-11-28

,我想创建名为“ fixing”的第三列,该列将在“ start_date”之前2个工作日。我正在尝试:

dates_table['fixing'] = move_date_by_days(self.dates_table['start_date'], -2, self.ccy, self.ccy)

但它返回AttributeError: 'Series' object has no attribute 'isoweekday'

请注意,例如,当我引用DataFrame的标量数据时,该功能可以正常工作

d1 = s1.dates_table.iat[0,0]
move_date_by_days(d1, -2, 'pln', 'pln')

它返回我所期望的:datetime.date(2020, 1, 29)

任何提示,请问如何在数据框的整个列上使用该功能?

1 个答案:

答案 0 :(得分:1)

IIUC,为什么不使用offsets.BDayoffsets.CustomBusinessDay,它们使用holidays的列表:

df['fixing'] = df['start_date'] - pd.offsets.BDay(2)
df['fixing'] = df['start_date'] - pd.offsets.CustomBusinessDay(2, holidays=holidays['pln'])

[出]

  start_date   end_date     fixing
0 2020-01-31 2020-04-30 2020-01-29
1 2020-04-30 2020-07-31 2020-04-28
2 2020-07-31 2020-10-31 2020-07-29
3 2020-10-31 2020-11-28 2020-10-29