Python 如何在不同条件下过滤数据帧

Python 如何在不同条件下过滤数据帧,python,pandas,Python,Pandas,从输入创建输出数据帧,在每个id的target==1时第一次筛选行,或者在target为1的每个id中删除连续出现的字,但是在target=1之前保留target中的所有0,并在没有1的位置保留一组id,例如a0 输入 输出 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

从输入创建输出数据帧,在每个id的target==1时第一次筛选行,或者在target为1的每个id中删除连续出现的字,但是在target=1之前保留target中的所有0,并在没有1的位置保留一组id,例如a0

输入

输出

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
使用np.argmax获取第一个元素的索引是可行的,但如何将所有行保留为0,其中每个id没有target=1 上一篇文章使用不同的数据集,使用np.argmax获取第一个元素的索引,但如何将所有行保留为0,其中每个id没有target=1 使用不同数据集的上一篇文章首先对数据帧进行排序

df.sort_values(['ID', 'date'], inplace=True)

# use cumsum to calculate how many times the target eq 1
df['tag'] = df['target'] == 1 
df['tag'] = df.groupby('ID')['tag'].cumsum()

# for every group use shift(1) to include the first 1
df['tag2'] = df.groupby('ID')['tag'].shift(1).fillna(0)
cond = df['tag2'] == 0
df[cond]
结果:

   ID        date  target  tag  tag2
0  a0  2019-11-01       0  0.0   0.0
1  a0  2019-12-01       0  0.0   0.0
2  a0  2020-01-01       0  0.0   0.0
3  a1  2019-11-01       0  0.0   0.0
4  a1  2019-12-01       0  0.0   0.0
5  a1  2020-01-01       1  1.0   0.0
8  a2  2019-11-01       0  0.0   0.0
9  a2  2019-12-01       1  1.0   0.0
df:

首先对数据帧进行排序

df.sort_values(['ID', 'date'], inplace=True)

# use cumsum to calculate how many times the target eq 1
df['tag'] = df['target'] == 1 
df['tag'] = df.groupby('ID')['tag'].cumsum()

# for every group use shift(1) to include the first 1
df['tag2'] = df.groupby('ID')['tag'].shift(1).fillna(0)
cond = df['tag2'] == 0
df[cond]
结果:

   ID        date  target  tag  tag2
0  a0  2019-11-01       0  0.0   0.0
1  a0  2019-12-01       0  0.0   0.0
2  a0  2020-01-01       0  0.0   0.0
3  a1  2019-11-01       0  0.0   0.0
4  a1  2019-12-01       0  0.0   0.0
5  a1  2020-01-01       1  1.0   0.0
8  a2  2019-11-01       0  0.0   0.0
9  a2  2019-12-01       1  1.0   0.0
df:


问得好。我相信Ferris的答案可能是一种优雅且计算效率高的方法。另一种直观的方法是考虑在数据帧上使用apply函数为排序后的数据帧中的每个组生成索引,直到我们应该在输出中包括哪一行

df["ind"]=df.index

upto_id_index = df.groupby("ID").apply(lambda x: x[(x["target"]==1)]["ind"].min() if (x["target"].sum()>0) else x["ind"].max())

df[df.apply(lambda x: x["ind"]<= upto_id_index.loc[x["ID"]], axis=1)]

问得好。我相信Ferris的答案可能是一种优雅且计算效率高的方法。另一种直观的方法是考虑在数据帧上使用apply函数为排序后的数据帧中的每个组生成索引,直到我们应该在输出中包括哪一行

df["ind"]=df.index

upto_id_index = df.groupby("ID").apply(lambda x: x[(x["target"]==1)]["ind"].min() if (x["target"].sum()>0) else x["ind"].max())

df[df.apply(lambda x: x["ind"]<= upto_id_index.loc[x["ID"]], axis=1)]

我没有真正了解您的查询,但您可以使用df.wherecondition来解决问题o:对于每个ID,按日期排序,然后在第一次出现'target==1'后删除所有行(如果有)?我没有真正了解您的查询,但您可以使用df.wherecondition来解决问题o:对于每个ID,按日期排序,然后在第一次出现“target==1”后删除所有行(如果有)?