从熊猫中的两个功能计算日期功能



您好,我想从date_startdate_end中计算duration的新功能。如果合同尚未结束,我使用今天的日期计算它。我的问题是我的 for 循环已经运行了 1 小时,我只有 200K 行。 我的代码出了什么问题(也许(? 有没有其他更简单的方法?

dftopyear['duration'] = ''
for x in dftopyear.Date_resil:
if x == pd.isnull(np.datetime64('NaT')): # this mean contract not yet ended
dftopyear['duration'] = dt.datetime.today().strftime("%Y-%m-%d") - dftopyear['date_start'] 
else: # this mean contact ended 
dftopyear['duration'] = dftopyear['Date_end'] - dftopyear['date_start']

这里有一个主要问题是,当你做减号dftopyear['date_start']时,它对整个数据帧做负号。

您需要一个索引定位器来指向单个值,而不是整个系列:

dftopyear['duration'] = ''
for i,x in enumerate(dftopyear.Date_resil):
if pd.isnull(x):
dftopyear.iloc[i, 'duration'] = dt.datetime.today().strftime("%Y-%m-%d") - dftopyear.iloc[i, 'date_start'] 
else: 
dftopyear.iloc[i, 'duration'] = dftopyear.iloc[i, 'Date_end'] - dftopyear.iloc[i, 'date_start']

或者更蟒蛇的方式:

dftopyear['duration'] = ''
for i,x in enumerate(dftopyear.Date_resil):
end_day = dt.datetime.today().strftime("%Y-%m-%d") if pd.isnull(x) else dftopyear.iloc[i, 'Date_end']
dftopyear.iloc[i, 'duration'] = end_day - dftopyear.iloc[i, 'date_start']

最新更新