python - 修改熊猫数据框中的日期列计算
问题描述
我有一个看起来像这样的数据框
我需要调整time_in_weeks
34 号条目的列。当有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 日,则不要执行任何计算。
解决方案
问题不是很清楚。如果我解释错误,很高兴纠正。
尝试使用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)
推荐阅读
- android - 如果更改包 ID 但旧包 ID 工作,Google Maps Api 无法识别/工作 -Android 工作室
- yourls - 您的:404 和目录问题
- java - 线程和字符串生成器
- apache-nifi - NIFI - ListenTCP 最大连接数设置 - 将 IoT 扩展到 10k
- python - socket.gaierror: [Errno -2] 将变量而不是静态地址分配给 sendto() 函数时,名称或服务未知
- asynchronous - 如何在颤振中完成所有以前的异步功能?
- python - SSH 脚本返回 ascii 十六进制代码
- react-native - 使用部分列表和平面列表反应原生条件渲染
- rest - 自定义操作中的 API PLATFORM 自定义标识符
- batch-file - 如何使用批处理脚本在两个模式之间提取字符串?