从输入创建输出数据帧,在每个id的target==1时第一次筛选行,或者在target为1的每个id中删除连续出现的字,但是在target=1之前保留target中的所有0,并在没有1的位置保留一组id,例如a0
输入
df = pd.DataFrame({'ID': ['a0','a0','a0','a1', 'a1', 'a1', 'a1', 'a1', 'a2', 'a2', 'a2', 'a2'],
'date': [ '2019-11-01',
'2019-12-01',
'2020-01-01',
'2019-11-01',
'2019-12-01',
'2020-01-01',
'2020-02-01',
'2020-03-01',
'2019-11-01',
'2019-12-01',
'2020-03-01',
'2020-04-01'],
'target': [0,0,0,0, 0, 1, 1, 0, 0, 1, 0, 1]})
输出
ID date target
a0 2019-11-01 0
a0 2019-12-01 0
a0 2020-01-01 0
a1 2019-11-01 0
a1 2019-12-01 0
a1 2020-01-01 1
a2 2019-11-01 0
a2 2019-12-01 1
问得好。我相信Ferris的答案可能是一种优雅且计算效率高的方法。另一种直观的方法是考虑在数据帧上使用“apply”函数为排序后的数据帧中的每个组生成索引,直到我们应该在输出中包括哪一行
首先对数据帧进行排序
结果:
df:
使用
np.argmax
获取第一个元素的索引是可行的,但是如何将所有行保留为0,其中每个id没有target=1 使用不同数据集(Pandas advanced groupby and filter by date)的上一篇文章相关问题 更多 >
编程相关推荐