【问题标题】:compute date feature from two feature in pandas从 pandas 中的两个特征计算日期特征
【发布时间】:2020-05-17 05:46:10
【问题描述】:

您好,我想从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']

【问题讨论】:

    标签: python pandas datetime for-loop


    【解决方案1】:

    这里有一个主要问题是,当您执行减号 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']
    

    或者更pythonic的方式:

    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 名称。谢谢
    • 你是对的。如果您的日期列已经是日期时间,则实际上只需要 dt.datetime.today() 。我会在答案中更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多