您好,我想duration
从date_start
和计算一个新功能date_end
。如果合同尚未结束,我将使用今天进行计算。我的问题是我的for循环已经运行了1个小时,我只有20万行。我的代码有什么问题(也许)?还有另一种方法可以使此操作更简单吗?
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']时,它对整个DataFrame进行减号。
您需要一个索引定位器来指向单个值,而不是整个序列:
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']
或更Python的方式:
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']
谢谢,尝试一下。我的NaT值输入完成。
我有这个错误
ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
尝试使用我更新的答案。我认为第一次发布有错字,后来被更正。
我看到了问题并立即解决,iloc只接受整数,我用轴1的索引替换了var名称。
你是对的。如果您的日期列已经是datetime,则实际上仅需要dt.datetime.today()。我会在答案中更新。