0

我在 327 条记录的数据集中有 2 列:

 #   Column                     Non-Null Count  Dtype         
---  ------                     --------------  -----               
 0   JD                         327 non-null    datetime64[ns]       
 1   CD                         312 non-null    Int64

我想生成第三个 ( ['theoretical_eoc']),它给我保存的日期[JD]加上[CD]. 但是当我使用以下方法定义这个新列时:

df['theoretical_eoc'] = turnover.apply(lambda x: x.JD + relativedelta(months=x.CD), axis=1)

我收到以下错误消息:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NAType'

因此,我定义了一个函数NaT,以防任何列中的一个值是 NA:

def rd_na(a, b):
    if pd.isnull(a) or pd.isnull(b):
        pd.NaT
    else:
        a + relativedelta(months = b)

但是当我应用它时:

df['theoretical_eoc'] = turnover.apply(lambda x: rd_na(x.JD, x.CD), axis=1)

结果是一个充满None值的列,当我期待datetime64[ns]一些NaT. 我究竟做错了什么?我怎么能完成这个任务?

4

1 回答 1

1

您缺少rd_na函数中的返回值

def rd_na(a, b):
    if pd.isnull(a) or pd.isnull(b):
        return pd.NaT
    else:
        return a + relativedelta(months = b)

考虑在处理时使用 pandas 的 DateOffsetpd.NaT

from pandas.tseries.offsets import DateOffset

df['theoretical_eoc'] = turnover.apply(lambda x: x.JD +
                                       DateOffset(months=x.CD), axis=1)
于 2020-04-14T19:43:14.580 回答