首页 > 解决方案 > 修改熊猫数据框中的日期列计算

问题描述

我有一个看起来像这样的数据框

在此处输入图像描述

我需要调整time_in_weeks34 号条目的列。当有uniqueid一个不同的副本时,rma_created_date这意味着发生了一些故障。需要更改 34 以计算新的最近rma_created_date(在本例中为 2020-10-15)之间的周数并减去rma_processed_date上述行 2020-06-28 之间的周数。

我希望这对我正在尝试做的事情有意义。

到目前为止,我这样做了

def clean_df(df):
    '''
    This function will fix the time_in_weeks column to calculate the correct number of weeks
    when there is multiple failured for an item.
    '''
    
    # Sort by rma_created_date
    df = df.sort_values(by=['rma_created_date'])

现在我需要执行上面描述的操作,但我对如何执行此操作有点困惑。特别是考虑到我们可能有多个失败,而不仅仅是 2 个。

我应该得到这样的东西作为输出返回

在此处输入图像描述

正如您所看到的那样,发生了什么事34是它被更改为在2020-10-15和之间的周数2020-06-26

这是另一个包含更多行的示例

在此处输入图像描述

使用建议的表达式

df['time_in_weeks']=np.where(df.uniqueid.duplicated(keep='first'),df.rma_processed_date.dt.isocalendar().week.sub(df.rma_processed_date.dt.isocalendar().week.shift(1)),df.time_in_weeks)

我明白了

最后说明:如果日期是 1900 年 1 月 1 日,则不要执行任何计算。

在此处输入图像描述

标签: pythonpandas

解决方案


问题不是很清楚。如果我解释错误,很高兴纠正。

尝试使用np.where(condition, choiceif condition, choice ifnotcondition)

#Coerce dates into datetime
df['rma_processed_date']=pd.to_datetime(df['rma_processed_date'])
df['rma_created_date']=pd.to_datetime(df['rma_created_date'])

#Solution    

df['time_in_weeks']=np.where(df.uniqueid.duplicated(keep='first'),df.rma_created_date.sub(df.rma_processed_date),df.time_in_weeks)

推荐阅读