python-3.x - 从具有相应 Boolean-Updated2x 的最新 ID 中获取日期
问题描述
我正在尝试查找具有相应 True 值的最新 ID 的相应日期
我已经使用 df.id.rolling 在我的日期范围窗口中找到我想要的重复项。我只需要确定重复项与最近出现的重复项之间的距离。
这就是我开始 df 的样子
df_input:
date id duplicate
1/10/18 1 true
1/12/18 2 true
1/20/18 1 false
1/31/18 1 false
这就是我想要达到的目标
df_output:
date id duplicate most_recent
1/10/18 1 true Nan
1/12/18 2 true Nan
1/20/18 1 false 1/10/18
1/31/18 1 false 1/10/18
任何提示都是有帮助的!
编辑:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~
感谢您的提示,但这似乎没有找到最近的实例,只有系列中的第一个实例返回第一个事件:
date id duplicate most_recent
0 1/10/18 1 True NaN
1 1/12/18 2 True NaN
2 1/20/18 1 False 1/10/18
3 1/31/18 1 False 1/10/18
4 2/1/18 1 True Nan
5 2/8/18 1 False 1/10/18
我在找:
date id duplicate most_recent
0 1/10/18 1 True NaN
1 1/12/18 2 True NaN
2 1/20/18 1 False 1/10/18
3 1/31/18 1 False 1/10/18
4 2/1/18 1 True Nan
5 2/8/18 1 False 2/1/18
感谢您的帮助,我认为我没有完全意识到或完全解释我的问题。更新了~~~~~~
提供的编码有效,所以也许我应该重新发布,但我需要能够找到最新的并附加一列,然后我需要能够根据 If + For 循环语句中列出的条件再次找到它。请参阅下面的代码示例
list2 = []
df.loc[~df.duplicates,'most_recent']=df['date'].where(df.duplicates).groupby(df['id']).ffill()
for index, row in df.iterrows():
dup = row['duplicates']
date = row['date']
ndate = row['most_recent']
d1 = date - ndate
if d1 > timedelta(days= 14):
x= True
if x == True:
list2.append(x)
else:
list2.append(dup)
df.loc[~df.duplicates,'most_recent']=df['date'].where(df.duplicates).groupby(df['id']).ffill()
示例输出:
date id duplicate most_recent
0 1/10/18 1 True NaN
1 1/12/18 2 True NaN
2 1/20/18 1 False 1/10/18
3 1/31/18 1 False 1/10/18
4 2/1/18 1 True Nan
5 2/8/18 1 False 2/1/18
一些代码
date id duplicate most_recent
0 1/10/18 1 True NaN
1 1/12/18 2 True NaN
2 1/20/18 1 False 1/10/18
3 1/31/18 1 False 1/10/18
4 2/1/18 1 True Nan
5 2/8/18 1 True 2/1/18
解决方案
我会做什么用ffill
df.loc[~df.duplicate,'most_recent']=df['date'].where(df.duplicate).groupby(df['id']).ffill()
df
Out[740]:
date id duplicate most_recent
0 1/10/18 1 True NaN
1 1/12/18 2 True NaN
2 1/20/18 1 False 1/10/18
3 1/31/18 1 False 1/10/18
推荐阅读
- python - 绘制平面及其法线
- git - 如何将 Git LFS 文件的旧版本打印到标准输出(LFS 的 git show / git cat-file)?
- python - 如何使用 pandas 在 python 中读取 csv 文件?
- android - ReactNative 应用程序的富文本编辑器
- android - 将 RecyclerView 项目更改为高于所有其他项目
- python - 如何使用 python boto3 将文本文件内容作为邮件正文发送?
- mysql - MySQL - 退出存储过程
- elasticsearch - 停止 Logstash 时 Elasticsearch 已创建索引
- java - 如何在 if 块内重构 Single/Observable 的公共映射
- gnuradio - GNU Radio BPSK BER 模拟:RRC 脉冲幅度归一化